One write, a million reads: random base62 codes, layered caching and Firestore
A shop creates one Diwali promo link in the morning and sends it by SMS. By evening, say a million people have clicked it. That is one write and a million reads, and every click should feel instant.
The problem
A URL shortener looks simple: store a code, look it up, redirect. The difficulty is in the shape of the traffic and in a few details:
- Unique codes. Two links must never get the same code, even if they are created at the same moment.
- Read-heavy traffic. If every click hits the database, cost and latency grow with popularity, and one viral link can become a hotspot.
- Storage choice. Picking a heavier database than the data needs means running replicas and, later, a sharding project for no reason.
To size it, I start with assumptions. Say 100 million new links a month, which is about 40 creates a second. With a 100:1 read-to-write ratio, that is about 4,000 redirects a second. The system is read-heavy, so the redirect path gets the most attention.
The solution
Two endpoints: POST /shorten returns sho.rt/aB3x9, and GET /aB3x9 redirects.
Create path
Load Balancer, then API Gateway, then Cloud Run, then Firestore. The gateway sits in front of /shorten only. It checks the API key and rate-limits, so a bot sending thousands of creates gets 429s. Redirects skip the gateway, because they must be fast.
Short code generation
I use a random 7-character base62 code (a-z, A-Z, 0-9). 62^7 is about 3.5 trillion possible codes.
for attempt in range(3):
code = random_base62(7)
try:
firestore.collection("links").document(code).create({"long_url": url, ...})
return BASE_URL + "/" + code
except AlreadyExists:
continue # rare collision: try a new code
The code is the Firestore document ID, and create() fails if that ID already exists. The check and the write happen as one atomic step, so two creators cannot both win. Even after a billion links, only about 1 in 3,000 creates would hit a collision and retry. A custom alias that is already taken returns 409 instead of retrying.
A counter needs a separate ID service, since Firestore has no auto-increment, and a truncated hash still collides.
Storage: Firestore
The data is one collection: document ID is the short code, with fields long_url, user_id, created_at and expires_at. Only key lookups, no joins. Firestore gives atomic uniqueness, a TTL policy for expiry, automatic scaling and multi-region availability, with nothing to resize or shard. Cloud SQL would work too, but it brings replicas, failover and a future sharding project. Bigtable is built for far higher throughput and has a per-node minimum cost; it fits click events better than the link table.
One detail: TTL deletion can lag, so the app also checks expires_at on read.
Redirect path: layered caching
Cloud CDN, then Load Balancer, then Cloud Run, which checks Memorystore (Redis) first and reads Firestore only on a miss.
For a viral link, the first click reads Firestore and later clicks come from Redis. A CDN can also cache the redirect itself, since it is a tiny response that is the same for every user, as long as the origin sends an explicit max-age.
301 or 302
A 301 is cached by browsers, so later clicks may never reach my server. A 302 asks the server every time. I use 302 when the business needs click counts or editable links, and keep a short CDN TTL so edits go live quickly. Clicks are published to Pub/Sub without waiting and loaded into BigQuery. Clicks answered by the CDN are counted from load balancer logs through a log sink, since those requests never reach Cloud Run.
Trade-offs and limits
- Per-operation billing makes the cache mandatory. Firestore bills per read, so a dropping Redis hit ratio raises the bill as well as latency. I would alert on both.
- Never keep a click counter in the link document. One document supports roughly one sustained write per second. Count clicks in BigQuery.
- Editing a link clears caches in order. Firestore first, then delete the Redis key, then invalidate the CDN path. A 301 already cached in a browser cannot be cleared at all.
- Revisit the database if needs change. If accounts, billing or team reports with joins appear, I would add Cloud SQL for that data only.
- Short links get abused. A production shortener should scan destinations for malware and phishing.
Takeaway
A URL shortener is read-heavy, so design the redirect path first.
Random base62 codes with an atomic create give uniqueness without a counter service.
CDN and Redis absorb the reads; Firestore stays the simple source of truth.





Top comments (1)
The 302 choice is the right call for a shortener, but it creates a tension with the click counting you mention later: once Cloud CDN caches that 302, those clicks never reach Cloud Run, so counting from app logs — even in BigQuery — undercounts exactly the viral links you most want to measure. The fix I've used is to count from the CDN access logs exported to BigQuery instead of from the app, and treat the app-side count as a lower bound. Curious whether you'd keep the CDN cache and move counting to the edge, or drop CDN caching for links where accurate counts matter.