Building “Infinity”: What a URL Shortener Taught Me About Real Backend Systems
Every URL shortener tutorial ends in the same place. A long URL goes in, a short code comes out, and a redirect happens on lookup. You can build that in an afternoon.
I wanted to know what comes after “it works.” So I built one called Infinity, first with FastAPI, PostgreSQL, and Redis, then again in Go. Writing the endpoints was the easy part. Most of my time went into measuring them, breaking them, and finding out which of my conclusions were wrong.
(One thing about the order of events. I built this before I knew any system design. There was no architecture diagram on day one. I added things because the next feature needed them, and then a problem would show up and I would go looking for how other people solved it. The cache layers, the connection pool sizing, the benchmark methodology in this post all arrived that way: build first, hit the problem, search for the reason, learn the design behind it afterward. This post follows the same order.)
The code is on GitHub. This post is the log: the numbers, the dead ends, and the bugs that only appeared on paths I had not tested.
Everything from “The starting point” through “Deploying, and the free-tier reality check” describes the Python version. I left it in place because the bugs and measurements are the point. The Go port is near the end. It has the same endpoints, the same cache layers, and the same behavior. All Go numbers in this post are local.
The starting point
The core is deliberately small:
POST /shortentakes a long URL and returns a short code.GET /{short_code}redirects to the original URL.GET /statsshows live hit counts for L1, L2, and the database.POST /seed_coldinserts brand-new codes straight into PostgreSQL for cold-path tests.
PostgreSQL stores the mappings. Redis sits in front of it as an L2 cache. An in-process LRU cache (least recently used) with a TTL (time to live) sits in front of Redis as L1. A small browser frontend fires real concurrent requests at the app.
client
│ HTTP
▼
┌─────────────────────────────────────────────────────────────┐
│ FastAPI · async · uvicorn workers │
│ each worker owns its own L1 and /stats counters │
└──────────────────────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ L1 cache · in-process LRU · per worker · TTL 60 s │
└──────────────────────────────┬──────────────────────────────┘
│ miss
▼
┌─────────────────────────────────────────────────────────────┐
│ L2 cache · Redis · shared across all workers · TTL 3600 s │
└──────────────────────────────┬──────────────────────────────┘
│ miss
▼
┌─────────────────────────────────────────────────────────────┐
│ PostgreSQL · source of truth │
└─────────────────────────────────────────────────────────────┘
The Python version used async SQLAlchemy with asyncpg and redis.asyncio. The Go version uses pgx and go-redis. The endpoints, status codes, schema, cache TTLs (60 seconds for L1, 3600 seconds for L2), and frontend are the same.
I picked a URL shortener because the domain is easy. That left me free to spend my time on the parts I actually wanted to learn: caching correctness, concurrency, connection pools, and whether a benchmark is measuring what its name says it is.
The first benchmark, and the conclusion I got wrong
Before any debugging, I ran hey and wrote down the results. The command was hey -n 5000 -c 100 -disable-redirects.
| Scenario | Req/sec | Avg latency | p99 |
|---|---|---|---|
| Single worker | ~317 | ~305 ms | ~657 ms |
| 4 workers | ~1,919 | ~49 ms | ~115 ms |
| Redis (warm) | ~1,500 | ~58 ms | ~130 ms |
The p99 column is the latency that 99% of requests were at or below. From that table I concluded four things:
- Worker scaling mattered most. Going from 1 to 4 workers raised throughput about 6x.
- Redis did not help. It added overhead without a benefit.
- Caching depends on context. It pays when the database is remote, under heavy load, or spread across multiple instances.
- Optimize measured bottlenecks, not assumptions.
Those conclusions were reasonable from the numbers. The problem was the numbers.
Bug 1: the cache that was never read
The redirect handler looked correct at a glance. Check Redis, then fall back to PostgreSQL:
try:
cached_url = redis_client.get(short_code)
except:
cached_url = None
db_url = db.query(models.URL).filter(models.URL.short_code == short_code).first()
Read it again. cached_url is fetched from Redis, and then nothing checks it. The code falls through to the PostgreSQL query whether the cache had the answer or not.
This is easy to write because it does not crash. It is syntactically valid. It just does extra work on every request, forever, until something makes you look.
The fix was one branch:
if cached_url:
return RedirectResponse(cached_url)
That branch goes right after the cache read, before the database is touched.
Now the first table makes more sense. The Redis (warm) row was not a cache hit. Every request still queried PostgreSQL, and paid for a Redis round trip on top. That is a good explanation for why it came in at ~1,500 req/sec, slower than the no-cache 4-worker run at ~1,919 req/sec. The cache was doing its job. The handler just never checked the result.
After the fix, the same general setup reached ~6,300 to 6,500 req/sec. The conclusion in my README had been built on a broken measurement. The benchmark ran cleanly and produced real numbers. It was measuring the wrong thing.
Bug 2: the dependency that only existed on my machine
redis_client.py did import redis, but redis was not in requirements.txt. My original machine had it installed globally, so nothing failed there. A fresh virtual environment did:
ModuleNotFoundError: No module named 'redis'
The fix was to add the package to requirements.txt. This one is boring, which is the point. If a fresh environment cannot install everything the project imports, the project only runs on your machine.
The benchmark that tested nothing
With the cache fixed, I wanted to know if it mattered. I ran:
hey -n 5000 -c 100 -disable-redirects http://127.0.0.1:8000/{short_code}
Every request came back 404. That was not a performance problem. I had left {short_code} in the URL as a literal placeholder. The request was asking for a code named {short_code}, which did not exist.
I created a real code with curl and ran it again. The result was ~6,300 to 6,400 req/sec with a median latency of ~15 ms, using 4 uvicorn workers.
Then I tried to compare cold and warm cache. I ran redis-cli FLUSHALL, benchmarked, and benchmarked again. The two runs came back almost identical: 6,303 and 6,421 req/sec.
My first thought was that the cache fix had done nothing. The real explanation is simpler. FLUSHALL empties Redis before the test starts. Then 100 concurrent requests start firing. The first request repopulates the cache almost immediately, so by request two the “cold” run is almost entirely warm. I was comparing warm with warm.
That test still taught me something. On localhost, with an indexed PostgreSQL lookup, the database is fast enough that Redis does not buy much for this workload. The cache becomes more valuable when the database is across a network or under sustained load. That part of my original conclusion survived.
Where the 6,300 ceiling comes from
So why did throughput stop around 6,300? The database was keeping up, and so was Redis. The limit was how the app was allowed to wait.
At that point the routes were plain def functions, not async def. FastAPI runs plain def routes in a thread pool. The default is 40 threads per worker. With 4 workers, the app could have 160 requests in flight. Request 161 waited for a free thread.
Three terms are easy to mix up:
- A worker is a separate OS process with its own Python interpreter and memory. Python's GIL lets only one thread per process execute bytecode at a time, so multiple workers are how you use multiple CPU cores.
- An event loop is a single thread that switches between async tasks whenever one is waiting on I/O. It does not run two things at once, but it can keep many connections moving because most of the time is spent waiting.
- A thread pool is the set of threads that run blocking
defroutes. Each thread blocks while it waits on Redis or PostgreSQL.
With 4 workers and 40 threads each, the old app had 160 places to wait. Anything beyond that queued. At c=500, it collapsed to ~983 req/sec with p99 at ~881 ms. No crash. No error. Just a long line.
In short: the coordination layer between the app and the database had a fixed capacity, and the queue showed up as latency.
Testing the thread-pool theory, and getting it wrong
The theory made a specific prediction. If 160 was the limit, throughput should stay flat and latency should stay tight up to c=160, then jump. I ran the sweep:
| c | Req/sec | Avg ms | p99 ms |
|---|---|---|---|
| 100 | 6,562 | 14.5 | 21.9 |
| 150 | 6,331 | 23.1 | 39.9 |
| 160 | 6,316 | 24.2 | 48.6 |
| 250 | 6,294 | 37.4 | 113.7 |
That is not what happened. There was no cliff at 160. Throughput stayed around 6,300 to 6,500 from c=100 to c=250. Latency climbed the whole time.
That shape means the app was already saturated near c=100. Once throughput is pinned, extra concurrency cannot be served in parallel. It waits, and the wait shows up as latency. Little's Law is the formal version: concurrency is roughly throughput times latency. If throughput stops moving and concurrency rises, latency has to absorb the difference.
The thread-pool math explains why a ceiling exists. It did not predict where this particular ceiling sat. I had a clean mechanical story, and the data did not fit it. I left the story in the post anyway, because the wrong prediction is more useful than a tidy one invented afterward.
Two loose ends came out of that sweep. At c=150 and c=160, only 4,950 and 4,960 of 5,000 requests completed. And the sharp collapse at c=500 was much worse than anything between c=100 and c=250. I had not found where that cliff starts. The first loose end gets resolved later, and the answer is not a server bug.
Half the machine was idle
After the sweep, I checked nproc. The machine had 8 CPU cores. The app had only ever run with --workers 4.
I bumped it to 8 and ran the same baseline:
| Workers | Req/sec | Avg latency | p99 |
|---|---|---|---|
| 4 | 6,562 | 14.5 ms | 21.9 ms |
| 8 | ~8,300 | ~11.2 ms | ~22.8 ms |
The result was repeatable: 8,321 and 8,250 req/sec on two separate runs, about 27% more throughput and lower average latency, with no code change.
That also answered a question from the sweep. At c=100, the app was partly CPU or worker bound. If it had been purely limited by the 160-thread pool, adding workers would not have moved a number that was already under 160. It moved, so there was more than one limit in play.
The 200 requests that were never sent
The more important test was the missing requests. At c=300 and c=400, exactly 4,800 of 5,000 completed, regardless of worker count:
| c (workers) | Req/sec | Avg ms | p99 ms |
|---|---|---|---|
| 300 (4) | 5,832 | 46.8 | 178.7 |
| 300 (8) | 7,108 | 38.7 | 117.4 |
| 400 (4) | 5,905 | 59.0 | 234.0 |
| 400 (8) | 6,330 | 50.5 | 137.1 |
Doubling the workers improved throughput and latency, but the missing count did not move by a single request. That zero effect was informative. If threads were the cause, more threads should have helped at least a little. They did not. So I went back to the benchmark tool's own output.
hey prints an error distribution when it captures failures. There was no error section. If the server had refused or timed out connections, the tool would have logged something. It logged nothing, because those requests were never sent.
hey -n 5000 -c 300 divides 5,000 requests across 300 workers and rounds down to a clean multiple. 300 times 16 is 4,800. The remaining 200 are never issued. I reran with the math aligned:
hey -n 4800 -c 300 -disable-redirects http://127.0.0.1:8000/ly1G6y
# 4800 / 4800 completed
100% completion. The server had never dropped a request at any concurrency I tested. The same rounding explains the 4,950 and 4,960 totals from the sweep. The output had been there the whole time.
The async rewrite and a cache in the process
Two changes went in together. Both aimed at the same two problems: the thread-pool ceiling and the network round trip to Redis.
The first change was the async rewrite. Every route moved from def to async def, backed by asyncpg for PostgreSQL and redis.asyncio for Redis. Instead of 40 threads per worker blocking on I/O, one event loop can keep thousands of requests in flight and only run the code that is ready.
The second change was an L1 cache. It is a hand-built LRU with a TTL that lives in the app's own memory, in front of Redis. The lookup order became:
L1 (in-process, no network) -> L2 (Redis) -> PostgreSQL
A Redis call on localhost is fast, but it is still a network round trip. If the hottest keys are already in process memory, skipping that round trip is close to free.
The benchmark hits one short code, ly1G6y, over and over. That is deliberate. A redirect service is read-heavy and skewed: a small number of links get most of the clicks. Hammering one code is a stand-in for that hot set.
Results
| Version | Req/sec | Avg latency | p99 |
|---|---|---|---|
| Pre-fix (buggy cache) | ~1,550 | ~58 ms | ~130 ms |
| Sync, cache fixed, 4 workers | ~6,400 | ~15.2 ms | ~25 ms |
| Sync, cache fixed, 8 workers | ~8,300 | ~11.2 ms | ~22.8 ms |
| Async + L1 cache, 8 workers | ~17,139 | ~5.4 ms | ~15.0 ms |
That is roughly 11x over the original buggy version and ~2.1x over the best sync result. The p99 came in at ~15 ms, barely above the average, which was the tightest distribution I had seen in the project.
With
--workers 8, there are 8 separate OS processes. Each one has its own L1 cache and its own copy of the/statscounters. The 17,139 req/sec result is async and L1 working together, with L1 doing a lot of the work once each worker's cache warms up. To separate the two, I would need to run async with L1 disabled. I have not done that, so I am not going to split the credit.
What is the cache actually doing?
The single-key number was real, but it was also the best case for an in-process cache. I needed two things: visibility into hit rates, and a benchmark that spreads traffic across many keys.
I added a small stats.py module with four counters: l1_hits, l2_hits, db_hits, and misses. Each one increments at the matching branch in the redirect handler and is exposed through GET /stats. The same per-worker limit applies here too: with 8 workers, /stats shows whichever worker answered that request, not a true sum across all 8.
GET /{short_code}
│
▼
┌─────────────────────────────────┐ ┌────────────────────────┐
│ 1 · L1 — in-process LRU │── hit ───► │ 307 redirect │
│ per worker · TTL 60 s │ │ stats: l1_hits │
└─────────────────┬───────────────┘ └────────────────────────┘
│ miss
▼
┌─────────────────────────────────┐ ┌────────────────────────┐
│ 2 · L2 — Redis │── hit ───► │ promote into L1 │
│ shared across workers · 3600 s │ │ 307 · stats: l2_hits │
└─────────────────┬───────────────┘ └────────────────────────┘
│ miss
▼
┌─────────────────────────────────┐ ┌────────────────────────┐
│ 3 · PostgreSQL │── found ─► │ populate L1 + L2 │
│ source of truth · indexed │ │ 307 · stats: db_hits │
└─────────────────┬───────────────┘ └────────────────────────┘
│ not found
▼
┌────────────────────────┐
│ 404 Not Found │
│ stats: not_found │
└────────────────────────┘
For multi-key load I wrote loadtest.py. It seeds 20 short codes, assigns each a weight from a Zipf distribution with skew 1.2 (a few codes get most of the requests, a long tail gets little), and fires concurrent requests weighted toward the hot codes.
The first result was strange:
Requests/sec: 720
Avg latency: 130ms
L1 hit rate: 98%
A 98% L1 hit rate should be fast. 720 req/sec was slower than the original pre-fix version. I tested four explanations in order.
- Shared
httpxconnection-pool limits. I raisedmax_connectionsandmax_keepalive_connections. No change. - Uvicorn access logging blocking the event loop. I disabled it with
--no-access-log. No meaningful change. - CPU contention between the client and the 8 server workers. I checked
htopduring a run. The cores were not pegged. - A shared connection-pool lock under 100-way concurrency. The clue was high latency with idle CPU, which looks like waiting on a lock. I gave each of the 100 concurrent workers its own
httpx.AsyncClient. Throughput went from 720 to 1,536 req/sec, about 2x.
That was a real improvement, but 1,536 was still far below the ~17,000 the server had already shown. What was left was Python itself. loadtest.py runs as one interpreter process. Generating load at 100-way concurrency has real overhead. This is why purpose-built load generators are written in compiled languages.
The hit rate measurement stayed valid. It reflects what the server did. The throughput number from that script was the client's ceiling, not the server's.
vegeta, redirects, and a 100% failure rate
To get a multi-key number without the Python client in the way, I switched to vegeta. It is written in Go like hey, and it can cycle through a weighted list of URLs instead of one target.
A small script, gen_vegeta_targets.py, seeds N codes and writes a Zipf-weighted target file. Each code appears a number of times proportional to its weight, then the file is shuffled.
The first run failed completely. Every request came back 404.
I went through the same process as before:
- Checked the target file for corruption with
cat -Aandxxd. Clean. No stray characters, no CRLF issue. - Tested a single hardcoded target, bypassing the file. Still 404. So the file was not the cause.
- Ran the same URL through
curl. It returned a clean 307 to the correct destination. The server and the data were fine. - Checked for snap sandboxing.
vegetawas installed withgo install, not snap. - Checked proxy environment variables. None were set.
- Decoded the raw response with
vegeta encode.
The headers said Server: cloudflare, Cf-Ray, and Cf-Cache-Status: HIT. The body was the “Example Domain” page from example.com.
That was the answer. vegeta follows redirects by default. Every seeded code in the project points at a fake path under https://example.com/..., which I had been using as filler test data. The server returned the correct 307. Then vegeta followed it to the real example.com, requested a path that does not exist there, and reported that site's 404 as if my server had failed.
hey never hit this because every hey run in the project had -disable-redirects. The equivalent vegeta flag, -redirects=-1, was missing.
vegeta attack -targets=targets.txt -rate=0 -max-workers=100 -redirects=-1 -duration=10s | vegeta report
The real multi-key number
Requests: 204,819 over 10s
Requests/sec: 20,480
Success ratio: 100%
Avg latency: 4.5ms
p99: 11.6ms
| Test | Req/sec | Avg ms |
|---|---|---|
Single key (hey) |
17,139 | 5.4 |
20 keys (loadtest.py) |
~1,536 | 59 |
20 keys (vegeta) |
20,480 | 4.5 |
The multi-key number came back higher than the single-key number, not lower. I am not going to invent a mechanism for that. The L1 cache uses one lock no matter how many keys it holds, so “less lock contention” does not explain it. The more likely answer is that vegeta is a slightly more efficient generator for this workload, or the difference is normal run-to-run variance. The useful finding is that realistic key spread did not hurt throughput.
I pulled /stats right after the 20,480 req/sec run:
{"total_requests":30655,"l1_hits":30601,"l2_hits":45,"db_hits":9,
"l1_hit_rate":0.9982,"l2_hit_rate":0.0015,"db_hit_rate":0.0003}
99.82% L1, slightly higher than the 98% from the slower run. More requests against the same 20 keys probably gave the cache more chances to stay warm relative to the cold start. I did not measure that separately.
Before blaming the database
Before chasing anything database-related, I checked the basics. \d url_shortener showed unique B-tree indexes on both short_code and long_url. EXPLAIN ANALYZE on the redirect query showed an Index Scan using ix_url_shortener_short_code, 0.035 ms execution time, two buffer hits, and no sequential scan.
The database was not the problem. That is a useful result too, because it removed a whole category of suspicion before I spent time on it.
The cold path: what happens on the first click
Every number up to this point measured hot traffic: codes that had already been requested, sitting in L1 or L2, answered without touching PostgreSQL. That is a real traffic pattern, but it is the best case.
The question I had not tested was simple. What does the app do the first time a link is clicked?
To guarantee a real miss, I wrote seed_cold_data.py. It bulk-inserts thousands of short codes directly into PostgreSQL, bypassing the API and both caches. The running app has never seen those codes, so every request is a genuine L1 and L2 miss.
The first cold run
Requests/sec: ~1,510-1,693
Avg latency: 59ms
Success rate: 91.6% (712 requests failed with HTTP 500)
A 500 on a cold miss should not happen. A slower successful request, sure. Not a server error. And this was a failure mode the hot path could never find, because a cache hit never asks the database pool for a connection.
The traceback gave the answer:
asyncpg.exceptions.TooManyConnectionsError: remaining connection slots are
reserved for roles with the SUPERUSER attribute
PostgreSQL's max_connections was at the default of 100. The app's pool was set to pool_size=20, max_overflow=20, which allows up to 40 connections per worker. With 8 workers, the app could ask for 320 connections, more than three times the limit.
The fix, and a skipped check
I changed the pool to pool_size=8, max_overflow=4, which gives 12 connections per worker and 96 across 8 workers, under the 100 limit. I also raised PostgreSQL's limit to 200 with ALTER SYSTEM SET max_connections = 200; and a restart.
I had planned to run pg_stat_activity first, to see which connections were actually open. I restarted PostgreSQL before that check, which cleared the state I wanted to look at. The fix worked, but I skipped the evidence. That is the kind of step that is easy to drop when the diagnosis feels obvious.
The contaminated rerun
The first retest looked great: ~7,400 req/sec and errors down to 3.4%. Then I looked at the request count. The run sent 36,990 requests against 20,000 seeded codes. vegeta had cycled through the target list almost twice, so a large part of the “cold” run was hitting codes that had already been warmed earlier in the same run. I threw that result away.
I reseeded with 50,000 codes and capped the duration so the total stayed under the seed count:
Requests/sec: 2,415
Avg latency: 41ms
Success rate: 99.89% (8 errors)
Success went from 91.6% to 99.89%. Throughput came in at 2,415 req/sec, lower than the contaminated 7,400, which is what should happen once the cache stops inflating the result. Eight errors remained.
A clean rerun
In a later session, with the same pool fix, a fresh 50,000-code reseed and a tightly capped run of 10,608 requests produced:
Requests/sec: 3,508-3,537
Avg latency: 28.264ms
p50: 23.2ms
p99: 136.9ms
Success rate: 100.00% (zero errors)
Zero errors, and higher throughput than the earlier clean run. My guess is that the earlier eight failures were near-miss connection pressure: requests briefly queuing for a pool slot without technically failing. That would add latency even to requests that succeeded, which fits the 41 ms average in that run. I did not measure it directly, so it stays a guess.
Hot vs cold
| Path | Req/sec | Avg ms | Success |
|---|---|---|---|
| Hot (cache hit) | ~20,480 | ~4.5 | 100% |
| Cold (cache miss) | ~3,500 | ~28 | 100% |
┌─ HOT PATH ─────────────────────────────────────────────────────────────┐
│ │
│ client ──► L1 hit ──► 307 redirect │
│ │
│ ~4.5 ms avg · ~20,400 req/s · no Redis hop, no DB query │
│ │
└────────────────────────────────────────────────────────────────────────┘
┌─ COLD PATH ────────────────────────────────────────────────────────────┐
│ │
│ client ──► L1 miss ──► L2 miss ──► Postgres ──► warm L1+L2 ──► 307 │
│ │
│ ~28 ms avg · ~3,500 req/s · one DB round-trip per request │
│ │
└────────────────────────────────────────────────────────────────────────┘
That is roughly a 6x gap between the hot and cold paths. It is the number the project had been missing since the first time I asked whether it behaved like a real URL shortener.
A cold path in the browser
The hot and cold split existed for vegeta, but the browser frontend only had a hot path. Every browser benchmark hit the same warm demo link, so a visitor could never see a first click.
I added POST /seed_cold?n=.... It bulk-inserts N new codes into PostgreSQL with ON CONFLICT DO NOTHING, skipping the API and the caches so /stats stays meaningful. The frontend fetches exactly as many codes as the benchmark will send, splits them into disjoint slices per worker, and fires every request at a code that has never been seen. Every request is an L1 miss, an L2 miss, and a database hit.
Now a visitor can watch the two paths diverge: L1 near 100% on the hot path, database near 100% on the cold path, and the same ~6x gap between them.
Deploying, and the free-tier reality check
Shipping the project meant choosing where it lives. The stack needs three services, and there is a free option for each:
| Piece | Service | Free tier |
|---|---|---|
| App | Render (Docker web service) | Free, sleeps after ~15 min idle |
| PostgreSQL | Neon | Free, no card required |
| Redis | Upstash | Free, TLS required |
Three changes were needed before it would run outside localhost:
browser · curl · hey · vegeta
│ HTTPS
▼
┌───────────────────────────┐ ┌──────────────────────────┐
│ Render · uvicorn × 2 │──────►│ Neon PostgreSQL │
│ FastAPI + L1 per worker │ │ source of truth · TLS │
└───────────────────────────┘ └──────────────────────────┘
│
▼
┌───────────────────────────┐
│ Upstash Redis · L2 │
│ rediss:// (TLS) · shared │
└───────────────────────────┘
all three services co-located in AWS us-east-2 (Ohio)
redis_client.pyhad a hardcodedhost="localhost". It now readsREDIS_URLand falls back to localhost. That also made Upstash'srediss://TLS connection string drop-in compatible.database.pyneeded to stripsslmodeandchannel_bindingfrom Neon's connection string, becauseasyncpgdoes not understand them, and passssl=Truefor remote hosts.- There was no
Dockerfile, even though the README mentioned one. I added one that installsrequirements.txtand runsuvicorn --workers 2on$PORT.
The deploy found two bugs that only exist with multiple processes.
The first was a startup race. Both uvicorn workers booted at the same time and both ran Base.metadata.create_all. One won. The other died with:
UniqueViolationError: duplicate key value violates unique constraint "pg_type_typname_nsp_index"
The app recovered on a later boot, but one worker dying on every cold start is not something to leave alone. I caught the “already exists” error in the lifespan handler and treated it as success. The table exists either way, so the loser can continue.
The second was in the documentation. The README said Redis host and port were configurable through environment variables, and that a Dockerfile and docker-compose setup existed. The client hardcoded localhost:6379, and there was no Dockerfile. The deploy forced those claims to become true. The article records the correction: env-driven config, a real Dockerfile, and an SSL-aware database URL builder.
The free tier is limited, and the numbers do not carry over:
- Render's free tier gives 0.1 CPU and 512 MB, and the service sleeps after about 15 minutes idle. The first request after sleep takes about 30 seconds.
- On the same code, deployed for free, I expect the hot path in the hundreds to low thousands of req/sec, and the cold path in the low hundreds with p99 in the tens of ms. Those are expectations, not measurements. The network hops between the app, Neon, and Upstash eat most of what local CPU gave back.
- The browser-driven benchmark is capped by the browser itself. The frontend says so on the page.
The deploy gave me the same code in a worse environment, and a way to show the difference.
That's it for the Python version.
The Go port: one process, all the cores
The Python version was the starting point, not the destination. Once the architecture was settled, I rewrote it in Go: net/http instead of FastAPI and Starlette, pgx and pgxpool instead of SQLAlchemy and asyncpg, go-redis instead of redis-py, and goroutines instead of uvicorn workers. The endpoints, status codes, cache TTLs, schema, and frontend stayed the same. It was a behavior-preserving port, not a redesign.
That made a clean comparison possible: same laptop, same PostgreSQL and Redis instances, same request path, same hey and vegeta flags, same day. The only variable was the implementation.
Hot path
One warm short code, hey -n 20000 -c 100 -disable-redirects:
| Metric | Python (8 workers) | Go (1 process) |
|---|---|---|
| Req/sec | ~16,000 | ~85,000 |
| Avg latency | 5.4-6.0 ms | 1.1 ms |
| p50 | 4.6-5.3 ms | 0.7-0.8 ms |
| p95 | 11.4-12.5 ms | 3.3 ms |
| p99 | 16.2-18.4 ms | 5.1-5.3 ms |
Three consecutive rounds:
| Round | Python | Go |
|---|---|---|
| 1 | 17,481 req/sec | 85,138 req/sec |
| 2 | 15,678 req/sec | 82,487 req/sec |
| 3 | 16,228 req/sec | 85,183 req/sec |
Roughly 5.2x the throughput and about 6x lower p50 latency, from one process instead of eight.
Cold path
60,000 freshly seeded, disjoint codes, so every request is a real L1 and L2 miss. The command was vegeta attack -rate=0 -max-workers=100 -redirects=-1 -duration=4s:
| Metric | Python (8 workers) | Go (1 process) |
|---|---|---|
| Req/sec | ~3,016 | ~32,100 |
| Mean latency | 32.9 ms | 2.7 ms |
| p50 | 29.2 ms | 2.2 ms |
| p95 | 54.7 ms | 6.4 ms |
| p99 | 133.8 ms | 9.0 ms |
Roughly 10.7x the throughput. Both runs were 100% successful. The contamination rule still applies: the attack total stayed under the 60,000 seeded codes, so the client never cycled back onto warmed codes. An earlier run that did cycle was discarded.
The Python numbers in this section are fresh side-by-side reruns, not the 20,480 req/sec and 3,500 req/sec results earlier in the post. Those came from a different traffic shape and a different session. I reran both implementations with the same tool and flags because mixing runs would make the comparison look cleaner than it is.
Why the Go version is faster
- No interpreter and no GIL. Python pays bytecode dispatch, object allocation, and reference counting on every request. The Go handler is compiled machine code, and the runtime schedules goroutines across all cores without a global lock.
- Goroutines instead of a process per worker. 100 concurrent connections are about 100 goroutines of a few KB each inside one process. The Python setup needs eight OS processes, each with its own interpreter, event loop, and L1 cache.
- Less framework per request. The Python request goes through Starlette's middleware stack, Pydantic response validation, and SQLAlchemy's ORM machinery. The Go path is a
ServeMuxlookup, a mutex-guarded map read, and a 307 write. Most of Python's ~4.5 ms p50 was overhead, not work. Go's p50 was ~0.7 ms. - Cheaper database round trips.
pgxspeaks the PostgreSQL wire protocol directly and reuses prepared statements over a small pool.asyncpgbehind SQLAlchemy adds a translation layer per query. This shows up most on the cold path: 33 ms to 2.7 ms mean. - Cheaper Redis calls and less allocation pressure.
go-redisreuses pooled connections without asyncio task and await overhead on every call. Go also allocates little per request and collects in parallel, while CPython builds and tears down an object graph per request under the GIL.
Do you need multiple Go processes?
The Python deployment ran uvicorn --workers 8, so the obvious first instinct is to carry that shape over. In Go it does not buy what it bought in Python, and the benchmarks show it.
Python needs one OS process per core because the GIL allows only one thread at a time to run bytecode. Go does not. Goroutines are multiplexed onto GOMAXPROCS OS threads, 8 here, one per logical CPU, all inside one process. A single Go process already uses the whole machine. Adding processes does not add CPU capacity to the hot path. It mostly duplicates the L1 cache, the /stats counters, and the database pool.
To test multiple processes, I used a benchmark-only SO_REUSEPORT patch so they could share one port. The shipped app binds a single port and runs one process.
| Setup | Hot path | Cold path |
|---|---|---|
| 1 process, default GOMAXPROCS (8) | ~78,000-81,000 req/sec | ~20,000 req/sec |
| 4 processes, default GOMAXPROCS | ~81,000-83,000 req/sec | not measured |
| 1 process, GOMAXPROCS=1 | ~76,000-79,000 req/sec | ~20,000 req/sec |
| 4 processes, GOMAXPROCS=1 | ~84,000-91,000 req/sec | ~41,000 req/sec |
| Python, 8 workers | ~16,000 req/sec | ~3,000 req/sec |
What the table shows:
- The hot path is not CPU-bound at these rates. One process restricted to a single core with
GOMAXPROCS=1still reached ~77,000 req/sec. During a four-process run the server processes sat at roughly 7% CPU, and two parallelheyclients totalled ~83,000, the same as one. Treat ~80,000 to ~90,000 as the ceiling of the test setup, not of the server.heyis a single-threaded Go client, and the loopback network is doing the limiting. - The cold path does scale with processes. Each miss blocks waiting on PostgreSQL, so more independent pools mean more requests in flight: ~20,000 to ~41,000 req/sec with four processes. This is the one case where copying the multi-process shape pays off.
- Processes cost database connections. Every process gets its own pool, and
MaxConnsis 12 in the Go port. Four processes can open 48 connections against PostgreSQL's 200 limit. Eight would be 96. That is the same class of bug the Python project found on the cold path, wherepool_sizetimes workers exceededmax_connections. Do that arithmetic before scaling processes. - Each process also gets its own L1 and its own
/stats. More processes mean a lower effective L1 hit rate for the same traffic, and a/statsendpoint that reports one replica instead of the whole service. Redis stays the shared L2, so correctness is unaffected. Only cache efficiency and observability change.
My recommendation:
- Run one Go process by default. It uses all available cores.
- Add processes only for cold-heavy or database-latency-bound traffic, and divide the connection-pool budget accordingly.
- Do not copy
--workers 8from the Python deployment. In Go it duplicates state without adding hot-path throughput. - If you scale out to separate containers, Redis becomes the shared cache layer and
/statsbecomes per-replica again.
One container detail matters. At the time, Go read the host's CPU count, not the cgroup quota. A container limited to 1 CPU on an 8-core host could still default to GOMAXPROCS=8 and thrash. Set GOMAXPROCS to the limit, for example ENV GOMAXPROCS=1. Co-located processes should split the cores: four processes on eight cores means GOMAXPROCS=2 each.
The multi-process runs used a throwaway database and a slightly different cold-path configuration, so their ~20,000 cold baseline is lower than the ~32,000 headline. Compare rows within the scaling table, not across tables.
What I took away
The URL shortener was easy to build. Trusting the numbers was the hard part. Twice I had a clean table and a confident conclusion, and twice the table was measuring something else: a cache that was never read, and a client that followed a redirect to a completely different website.
The bugs that mattered most were on paths I had not tested. A hot cache can hide a database connection pool that falls over on the first real cold traffic. A load generator can report a 100% failure rate and be wrong. Neither problem shows up if every test exercises the same narrow path.
The endpoints were the easy part. Everything underneath them is what I wanted to learn: the cache that was not being read, the pool that was too large for the database, the redirect that the load tester followed on its own. That is the part I am still learning.