Discover MCPs & agents
Loading MCPs and agents…
Loading MCPs and agents…
Spring Boot URL shortener taken from Docker Compose to Kubernetes + Terraform — a real 'vibe coding' learning example built with Claude Code
Jump to setup instructionsGitHub checked 568h ago - refresh overdue
This isn't a product, a portfolio piece, or something I'm asking you to use. It's a URL shortener that exists to answer one question: what does it actually look like to learn backend development by building something real, with an AI agent as a pairing partner instead of a chatbot you paste code into?
A little about why: I was a backend engineer, then moved into engineering management for long enough that I stopped writing real code day to day. Docker, Kubernetes, Terraform, a proper monitoring stack — none of that was "here's a refresher," it was genuinely new to me going in. This project is me testing, on myself, whether "build something real with an AI agent, then keep extending it" is actually a working way back into hands-on engineering — not a claim I'm making from the outside, an experiment I ran on myself, with the failures left in.
If you've asked ChatGPT or Claude "teach me backend development" and gotten a study plan that goes stale after a few days — that's the wrong use of the tool, and this repo is the alternative: don't ask an AI to teach you backend development, ask it to help you build something, then keep giving that thing more capabilities until you've accidentally learned backend development along the way.
That's literally the whole method here:
Pick a real problem, build the dumbest version that solves it. This started as: take a long URL, give back a short one, redirect when visited. A Spring Boot service, Postgres, a redirect endpoint. Nothing clever.
Give it a capability it's missing, one at a time, because you actually need it — not because a curriculum says so.
Every one of those was "huh, I wonder if I could—" not step 4 of a syllabus.
Do the work with an AI agent, don't outsource the thinking to one. Every commit here was written in collaboration with Claude — but "collaboration" meant debugging real crash loops, reading actual error messages, verifying claims against a live cluster instead of trusting that code compiled = code worked. Every step — including the mistakes (a race condition that crash-looped a pod, a monitoring config that was silently ignored, a memory limit that turned out to be too small) — is in the commit history and in CLAUDE.md, not cleaned up after the fact. Each of those mistakes is also written up as a compact decision record — trigger, rejected fix, tested remedy, and why — in INCIDENTS.md.
To the "software development is boring, don't bother" comments in that thread: fair, if your version of "learning backend development" is a CRUD tutorial you never deploy. It stops being boring the moment something you built breaks in a way you don't understand yet and you have to find out why — a pod that crash-loops because Kubernetes has no idea Postgres needs to start first, a Helm chart that silently ignores half your config because you guessed a field name wrong, a metric that should exist and doesn't. That's not busywork, that's the actual job, and it's genuinely fun in a way "watch a video, copy the code" never is.
Clone it. Read the commit history. Steal the approach for whatever you're actually curious about — it doesn't have to be a URL shortener.
⭐ If this is useful to you as a learning example, a star helps other people find it too.
Given a long URL, it generates a short code (or reuses the one it already gave that URL — shortened URLs are permalinks) and redirects to the original URL when that code is visited.
What started as a local Docker Compose app has grown into a full Kubernetes deployment with autoscaling and a Prometheus/Grafana monitoring stack, deployable either locally (minikube) or to a small AWS instance — all through Terraform.
k8s/src/main/java/com/alokeb/urlshortener/
├── UrlShortenerApplication.java # entry point, @EnableCaching
├── model/UrlMapping.java # JPA entity: id, shortCode, originalUrl, createdAt
├── repository/UrlMappingRepository.java # Spring Data derived queries
├── service/UrlShortenerService.java # dedupe + host-case normalization on shorten(),
│ # Redis-backed @Cacheable on resolve()
└── web/
├── UrlShortenerController.java # REST endpoints
├── ShortenRequest.java # POST request body
└── ShortenResponse.java # POST response body
src/main/resources/
├── application.properties # env-var-driven Postgres/Redis config, /actuator/prometheus
└── static/tester.html # simple browser form to shorten/test URLs
src/test/java/com/alokeb/urlshortener/
├── UrlShortenerApplicationTests.java # plain context-load smoke test
└── service/UrlShortenerServiceStressTest.java # see Testing below
Dockerfile # multi-stage build (Maven -> slim JRE runtime)
docker-compose.yml # app + postgres + redis, local dev only (see below)
.env.example # copy to .env and fill in real values (.env is git-ignored)
requests.http # REST Client (VS Code) requests for shorten + redirect
test-requests.sh # zero-dependency curl script exercising the same flow
k8s/ # plain kubectl manifests - namespace, Secret, Postgres, Redis, app, HPA,
│ # ServiceMonitor, a load-test Job, a Grafana dashboard ConfigMap pair,
│ # the load-test trigger service, and the Traefik Ingress
└── ...
terraform/ # deploys everything in k8s/ (plus the Helm monitoring stack) with
│ # one command, to either local minikube or AWS - see "Deploying" below
├── credentials.tfvars.example # copy to credentials.auto.tfvars, fill in AWS keys
├── terraform.tfvars.example # copy to terraform.tfvars to override any default
└── ...
Every tool below is cross-platform (Linux/macOS/Windows) — install whichever your OS's package manager or the linked installer prefers. You only need the ones for the path you're actually using (see the table under "Deploying").
| Tool | Get it |
|---|---|
| Docker | https://docs.docker.com/get-docker/ |
| kubectl | https://kubernetes.io/docs/tasks/tools/#kubectl |
| minikube | https://minikube.sigs.k8s.io/docs/start/ |
| Helm | https://helm.sh/docs/intro/install/ |
| Terraform | https://developer.hashicorp.com/terraform/install |
| conntrack (Linux only, needed by minikube's Docker driver) | usually available via your Linux distro's own package manager (e.g. conntrack on Debian/Ubuntu, conntrack-tools on Fedora/Arch) |
No local JDK or Maven needed for any path — the app is always built inside Docker.
Three ways to run this, from simplest to most complete:
| Path | What you get | Needs |
|---|---|---|
| Docker Compose | app + Postgres + Redis, no Kubernetes | Docker |
| Local Kubernetes | + autoscaling, monitoring dashboard | + kubectl, minikube, Helm (or Terraform to automate it) |
| AWS (example cloud target) | same as local K8s, but on a real internet-reachable server | + Terraform, an AWS account |
cp .env.example .env # first time only; edit in a real password
docker compose up -d --build
Starts three containers: app (port 8080), postgres, redis. Postgres/Redis also publish to 127.0.0.1 only (reachable from local tooling on this machine, never from the network).
Teardown: docker compose down (add -v to also wipe the Postgres volume).
If something's misbehaving after editing docker-compose.yml and a restart doesn't fix it, try docker compose up -d --force-recreate — a plain restart can leave stale network state behind when config changed but the image didn't.
Either apply the plain manifests by hand, or let Terraform do the whole thing (cluster included):
By hand:
minikube start --driver=docker --memory=20000
minikube addons enable metrics-server
docker build -t url-shortener-app:latest .
minikube image load url-shortener-app:latest
kubectl apply -f k8s/namespace.yaml -f k8s/secret.yaml -f k8s/postgres.yaml \
-f k8s/redis.yaml -f k8s/app.yaml -f k8s/hpa.yaml -f k8s/servicemonitor.yaml \
-f k8s/loadtest-trigger.yaml
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo add traefik https://traefik.github.io/charts
helm repo update
# root_url must match how you actually reach Grafana, not its in-pod address: the Overview
# dashboard's stress-test button calls a relative endpoint, and Grafana resolves those
# against root_url rather than the browser's origin - leave it at the localhost:3000 default
# and the button fires into the void. The 1s kube-state-metrics scrape is what makes the
# button's label flip quickly (see Autoscaling below); 30s is the chart default.
helm install monitoring prometheus-community/kube-prometheus-stack \
-n monitoring --create-namespace \
--set 'grafana.grafana\.ini.server.root_url=http://grafana.url-shortener.local:30080/' \
--set 'grafana.grafana\.ini.dashboards.min_refresh_interval=1s' \
--set 'kube-state-metrics.prometheus.monitor.interval=1s' \
--set 'kube-state-metrics.prometheus.monitor.scrapeTimeout=1s'
kubectl apply -f k8s/dashboards-configmap.yaml
# minikube has no built-in Traefik addon (unlike its nginx one) - see k8s/ingress.yaml's
# comment for why Traefik specifically, and why the port numbers below. Note service.spec.type,
# NOT service.type - this chart nests Service overrides a level deeper than most, and the
# wrong key is silently ignored rather than rejected (see INCIDENTS.md).
helm install traefik traefik/traefik -n kube-system \
--set ingressClass.enabled=true --set ingressClass.name=traefik \
--set service.spec.type=NodePort --set ports.web.nodePort=30080 --set ports.websecure.nodePort=30443
kubectl apply -f k8s/ingress.yaml
Note: k8s/loadtest-trigger.yaml depends on the load-test-script ConfigMap that k8s/load-test-job.yaml creates (see Autoscaling below) - applying that file at least once, by hand or via the trigger button, is needed before the trigger actually works. The Terraform path doesn't have this gap (terraform/loadtest_trigger.tf applies that ConfigMap unconditionally, up front).
Or via Terraform (see "Terraform" below for the full explanation) — from terraform/:
terraform init
terraform apply -target=null_resource.minikube_cluster -auto-approve # phase 1: cluster only
terraform apply -auto-approve # phase 2: everything else
Teardown:
kubectl delete namespace url-shortener monitoring # if deployed by hand
# or, if deployed via terraform:
terraform destroy -auto-approve
minikube stop # or `minikube delete` to remove the cluster entirely
Everything in k8s/ (Postgres, Redis, the app, the HPA, monitoring) only ever talks to "a Kubernetes cluster" — it has no idea whether that cluster is minikube or a cloud VM. AWS is provided as the one concrete, tested-locally reference implementation of "provision a cloud cluster for this," via terraform/aws.tf: it provisions a single EC2 instance running k3s (a lightweight, fully real Kubernetes distribution), then deploys the same app/Postgres/Redis/HPA into it. Adding another cloud provider later is a matter of writing one more file following that same shape (VM + firewall + SSH keypair + k3s install script + kubeconfig fetch) — see aws.tf's own comments for the pattern.
Minimum system requirements (this instance, or any machine running this stack): ~1 vCPU / ~1GB RAM without monitoring, ~2 vCPU / ~3GB RAM with it enabled. aws_instance_type (terraform/variables.tf) defaults to t3.micro, which meets the smaller tier and happens to also be AWS's free-tier-eligible size — a bonus, not the reason it was chosen. Any instance type meeting the requirement above works. Note: AWS's managed Kubernetes service (EKS) has no free tier at all (a flat ~$73/month for the control plane alone regardless of usage) — this deliberately runs k3s on a plain EC2 instance instead, specifically to avoid that. A card on file is still required by AWS even for free-tier usage, and leaving resources running past whatever limits apply to your account, or forgetting to tear down, will incur real charges.
This path is written carefully but has not been live-tested against a real AWS account (no credentials were available to verify it end-to-end while building it) — unlike the local minikube path, which was fully applied and destroyed successfully. Run terraform plan first (read-only, safe, costs nothing) to review what it would do before your first real apply, and keep an eye on the AWS Console while it runs the first time.
cd terraform
cp credentials.tfvars.example credentials.auto.tfvars # fill in real AWS keys
cp terraform.tfvars.example terraform.tfvars # uncomment deployment_target = "aws"
terraform init
terraform apply -target=null_resource.aws_kubeconfig -auto-approve # phase 1: provision EC2 + k3s
terraform apply -auto-approve # phase 2: everything else
enable_monitoring defaults to true, which needs the larger (~2 vCPU/~3GB) tier above — set enable_monitoring = false in terraform.tfvars if you're using an instance sized only to the smaller (~1 vCPU/~1GB) minimum, like the default t3.micro.
Teardown: terraform destroy -auto-approve — this deletes the EC2 instance and everything on it. Always run this when you're done to avoid ongoing charges.
apply commands?Terraform's provider configuration (the kubernetes/helm/kubectl blocks) has to be resolved before Terraform knows what resources exist — so it can't wait for a not-yet-created cluster the way individual resources can wait on each other. The first apply (targeted at just the cluster-bootstrap resource) exists purely to get a live cluster and valid kubeconfig in place; the second apply does everything else now that the provider blocks can actually connect. This is a real, documented Terraform limitation, not a workaround for a mistake in this config.
After that first cluster exists, subsequent terraform apply runs (e.g. after a code change) only need the single, normal command — the two-phase dance is only needed when the cluster itself doesn't exist yet.
An Ingress (k8s/ingress.yaml / terraform/ingress.tf) routes both the app and Grafana by hostname, so neither needs its own kubectl port-forward running. It targets Traefik specifically (not the more common ingress-nginx) because k3s — the AWS path's cluster — already ships Traefik built in; writing against it means the same Ingress objects work unmodified on both deployment targets. minikube has no equivalent built-in Traefik, so the local path installs it via Helm (terraform/bootstrap.tf's helm_release.traefik, or the manual helm install traefik ... step above for the by-hand path).
One-time step either way: point both hostnames at the right IP. Terraform can't portably edit /etc/hosts for you (OS-specific, needs elevated permissions), so this stays manual:
# Local (minikube):
echo "$(minikube ip) app.url-shortener.local grafana.url-shortener.local" | sudo tee -a /etc/hosts
# AWS (see "terraform output" for the instance's public IP):
echo "<EC2 instance public IP> app.url-shortener.local grafana.url-shortener.local" | sudo tee -a /etc/hosts
Then:
| Local (minikube) | AWS | |
|---|---|---|
| App / tester page | http://app.url-shortener.local:30080/tester.html | http://app.url-shortener.local/tester.html |
| Grafana | http://grafana.url-shortener.local:30080 | http://grafana.url-shortener.local |
The port difference is a real infrastructure difference, not an inconsistency: k3s's built-in ServiceLB binds Traefik straight to the node's port 80/443 (designed for exactly this bare-node case, no cloud load balancer needed), while the Helm-installed Traefik on minikube uses a NodePort instead of a LoadBalancer Service, since minikube's Docker driver never assigns a LoadBalancer Service a real external IP without a separate, permanently-running minikube tunnel process.
The Ingress above is the primary way to reach things now. kubectl port-forward still works as a fallback (e.g. if you haven't set up the /etc/hosts entries, or Ingress isn't deployed):
kubectl port-forward -n url-shortener svc/url-shortener-app 8080:8080 # app: http://localhost:8080
kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80 # Grafana: http://localhost:3000 (auto-logged in as admin)
For the AWS path, run export KUBECONFIG=terraform/generated/aws-kubeconfig first so kubectl points at the right cluster (terraform output prints this reminder too).
curl -X POST http://localhost:8080/api/urls \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/some/very/long/path"}'
Response:
{"shortCode": "7Sgvani", "shortUrl": "http://localhost:8080/7Sgvani"}
url must start with http:// or https://. Shortening the same URL again returns the same short code instead of minting a new one — matching is exact except the host is treated case-insensitively (Example.com and example.com dedupe to the same code; the path does not, since paths are case-sensitive by spec).
curl -i http://localhost:8080/7Sgvani
Returns a 302 redirect to the original URL (or 404 if the code doesn't exist).
With the stack running, open http://localhost:8080/tester.html for a simple form to shorten URLs and click through the results. It has to be loaded through the running app at that URL (not opened as a local file) — its JavaScript calls the API using a relative path, which only resolves correctly when served by the app itself.
requests.http — open in VS Code with the REST Client extension installed; click "Send Request" above each block../test-requests.sh [base-url] — plain curl, no extension needed.There's no fast local Maven test loop — see CLAUDE.md for why. All iteration goes through Docker.
UrlShortenerServiceStressTest is the real test suite: three small-scale stress tests against genuine Postgres/Redis via Testcontainers (not mocks) proving the cache actually shields the database under concurrent load, dedupe holds up across thousands of synthetic requests, and printing an actual cache-hit-vs-miss latency report. Needs a Docker daemon reachable from wherever it runs (Testcontainers spins up its own throwaway containers). To run it:
docker run --rm \
-v "$(pwd)":/app \
-v /var/run/docker.sock:/var/run/docker.sock \
-w /app \
-e TESTCONTAINERS_RYUK_DISABLED=true \
maven:3.9-eclipse-temurin-21 \
mvn test -Dtest=UrlShortenerServiceStressTest
(TESTCONTAINERS_RYUK_DISABLED sidesteps some sibling-container complexity when Testcontainers itself is running inside a container via the mounted Docker socket; the containers it spins up still get cleaned up via a JVM shutdown hook either way.)
UrlShortenerApplicationTests is the original bare context-load smoke test generated by Spring Initializr. It needs a live Postgres/Redis to pass and currently has no Testcontainers setup of its own, so it isn't run as part of any normal workflow here — mvn test with no -Dtest filter would try to run it too and fail without one.
The HPA (k8s/hpa.yaml) scales the app Deployment on CPU utilization. k8s/load-test-job.yaml generates real HTTP load (a mix of unique-URL writes and repeated cache-hit reads, run as parallel in-cluster Job Pods) to actually trigger it - either directly:
kubectl apply -f k8s/load-test-job.yaml
kubectl get hpa -n url-shortener -w # watch REPLICAS climb in real time
or with a click, from the Run / Stop Stress Test button on the Grafana Overview dashboard (see below). The Overview dashboard's Min replicas / Max replicas variables (top of the dashboard) control what the button actually does, not just labels: clicking it hits a small in-cluster trigger service (k8s/loadtest-trigger.yaml) that live-patches the HPA to those bounds (kubectl patch hpa) and scales the load-test Job's parallelism/completions to roughly match Max replicas — one load-generator Job pod per target replica, a simple heuristic for "enough aggregate load that the HPA has an actual reason to scale that high," not an exact CPU model. The trigger service is narrowly RBAC-scoped to Jobs and this one HPA in the url-shortener namespace; it has no other permissions.
The same button stops the test — it's one endpoint that toggles on whatever the Job's current state actually is, so the label flips between "▶ Run Stress Test" and "■ Stop Stress Test" to match. Two details make that feel immediate rather than laggy, both documented in INCIDENTS.md: the trigger service blocks until Prometheus reports the change (not just until the API server accepts it), which keeps Grafana's own button spinner up for the real duration instead of flashing for a moment and then sitting on a stale label; and kube-state-metrics is scraped every 1s rather than the chart's 30s default, since that scrape is what the label reads. Click-to-updated-label lands around 3s.
Delete the Job (kubectl delete job load-test -n url-shortener) to stop the load, or just click the button again. A later terraform apply resets the HPA back to app_min_replicas/app_max_replicas (terraform/variables.tf) — the dashboard's live patch is meant for poking at it interactively, not a permanent config change.
Expect roughly a 5-minute delay before the replica count starts falling, even though CPU drops within seconds and the load-test Job is deleted immediately. That's Kubernetes working as designed, not the dashboard lagging: the HPA applies a scale-down stabilization window (behavior.scaleDown.stabilizationWindowSeconds, default 300s) so that a brief dip in traffic can't cause it to tear down capacity it's about to need again. Scaling up has no such delay here — the defaults are deliberately asymmetric:
kubectl get hpa -n url-shortener url-shortener-app \
-o jsonpath='{range .status.conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'
# AbleToScale=True (ScaleDownStabilized) <- this is the HPA holding, on purpose
ScaleDownStabilized is the HPA telling you exactly that. If you want a demo that comes back down promptly, set behavior.scaleDown.stabilizationWindowSeconds to something like 30 in k8s/hpa.yaml (and the Terraform mirror) — but that's a demo-oriented choice, not a general recommendation: under real traffic a short window makes the Deployment flap on every brief lull, which is the exact thing the 300s default exists to prevent.
Two dashboards, auto-provisioned into Grafana via a labeled ConfigMap pair (k8s/dashboards-configmap.yaml / terraform/monitoring.tf - no manual "import" step) - no more ad-hoc PromQL against the bundled dashboards:
$pod variable. Click any row in the Overview dashboard's pod table to drill into that pod's detail view.mvn test -Dtest=UrlShortenerServiceStressTest and terraform validate/fmt -check on every push — right now nothing verifies any of this automatically; every check in this project (including everything in INCIDENTS.md) has been run by hand.terraform/aws.tf's comments for the pattern to follow)GitHub checked 16h ago - refresh overdue. Recently viewed repositories target hourly refresh.
Find a documented setup for your client. No sign-in, installation, or tool execution.
If this MCP is also published on mcpchannel.ai, you can subscribe from Browse and use the gateway config there instead.