Course contentsShow
← System Design
Lesson 1539 of 1,91937. Real-World System: URL ShortenerFree lesson

QR Code Generation

Dynamically generate QR codes for shortened URLs with caching to reduce computation costs at scale.

QR Code Generation

You'll learn how to dynamically generate QR codes for shortened URLs while keeping costs low at massive scale through smart caching.


What is QR Code Generation in URL Shorteners?

Once you've created a shortened URL, users often want a QR code — a scannable 2D barcode that encodes the URL. Instead of storing pre-generated images in your database, you generate them on-demand when requested. However, generating QR codes involves computational overhead (image encoding, error correction algorithms), so doing it fresh for every request becomes expensive at scale.

The solution? Generate once, cache aggressively.


How It Works

When a client requests a QR code for https://short.ly/abc123:

  1. Check cache first — look for a cached QR code image keyed by the short URL
  2. Cache hit → return the pre-generated image immediately (fast, cheap)
  3. Cache miss → generate the QR code on-the-fly, store it in cache (Redis, CDN), then return it
  4. Set an appropriate TTL matching your URL expiration policy

Since QR codes are immutable (the short URL never changes), they're perfect for long-term caching. Popular URLs might stay cached indefinitely; rarely accessed ones expire naturally.


Why Cache QR Codes?

  • CPU savings: QR generation involves matrix calculations and image encoding — expensive to repeat
  • Latency reduction: Cached images return in <5ms vs 50-100ms for generation
  • CDN-friendly: Static image assets can be edge-cached globally

Think of it like a photo printing service: printing the same picture 1,000 times is wasteful when you can print once and photocopy the rest.


Key Takeaway:
Dynamically generate QR codes on first request, then cache aggressively (in-memory or CDN) to eliminate redundant computation and serve millions of scans at minimal cost.