Knowledge / Computer Science and Engineering / Caching, queues and CDNs

Caching, queues and CDNs

Computer Science and Engineering (B.E./B.Tech) · Web, cloud and design · free study notes for exams, placements and interviews

In short

Caching keeps a copy of expensive data close to where it is needed, queues decouple a fast producer from a slower consumer, and a CDN pushes static content to servers near the user. Together they are the three cheapest ways to make a web system fast and resilient without buying a bigger database. Universities examine this under web technologies, cloud computing and distributed systems; placement interviews at Flipkart, Zomato, Swiggy, Paytm, PhonePe, Razorpay, Zoho, Freshworks, TCS Digital and Infosys Power Programmer ask it in almost every system-design round. Indian traffic patterns make it concrete: IRCTC Tatkal at 10:00, a BookMyShow ticket drop, or an IPL stream on JioHotstar all survive on cache hit ratio and queue depth, not on raw CPU.

Explained

What a cache is and the layers it lives in

Cache read and write strategies

Eviction, expiry and invalidation

HTTP caching and CDNs

Message queues and asynchronous processing

Putting the three together, and what to measure

Key points

Formulas and examples

Hit ratio H = hits / (hits + misses); Miss ratio M = 1 − H (dimensionless, often %)
Effective (average) access time T_eff = H × T_cache + (1 − H) × T_miss [ms]
(Simple model; if a miss also includes the cache lookup, T_miss = T_cache + T_origin)
Origin requests per second = (1 − H) × total RPS
Little's Law: L = λ × W (L = items in system, λ = arrival rate per second, W = time in system in seconds)
Utilisation ρ = λ / (c × μ) (μ = messages served per second per consumer, c = number of consumers); stable only if ρ < 1
Consumers needed c ≥ λ / μ (round up)
M/M/1 average wait in system W = 1 / (μ − λ); average number in system L = ρ / (1 − ρ)
Consumer lag = latest offset produced − offset committed by the consumer [messages]
Cache memory needed ≈ number of keys × (key + value + overhead) bytes
CDN egress cost = GB served × rate per GB (₹/GB); origin offload = 1 − (origin bytes / total bytes)

Example 1 - Effective latency from a cache. A product API serves 5,000 requests/s. Redis responds in 1 ms, the database in 40 ms. Hit ratio is 92%.

Example 2 - LRU trace (exam style). Cache of size 3, access sequence: A B C A D B E. Count hits and misses with LRU.

AccessCache after (MRU→LRU)Result
AAmiss
BB, Amiss
CC, B, Amiss
AA, C, Bhit
DD, A, C (evict B)miss
BB, D, A (evict C)miss
EE, B, D (evict A)miss

Example 3 - Sizing consumers with Little's Law. A Diwali sale produces order-confirmation emails at λ = 600 messages/s. One worker handles μ = 25 messages/s.

Example 4 - CDN offload and cost. A news site serves 20 TB a month: 18 TB static (images, JS, CSS) and 2 TB HTML. The CDN caches static content at a 95% hit ratio; HTML is not cached.

Example 5 - TTL and staleness budget. A cricket scorecard is cached for 10 s and fetched 12,000 times a minute.

// Cache-aside with a stampede lock and jittered TTL
async function getProduct(id) {
  const key = `product:v3:${id}`;              // v3 = version, cheap invalidation
  const hit = await redis.get(key);
  if (hit) return JSON.parse(hit);

  const lock = await redis.set(`${key}:lock`, '1', 'NX', 'EX', 10);
  if (!lock) {                                  // someone else is loading it
    await sleep(50);
    return getProduct(id);
  }
  const row = await db.findProduct(id);
  const ttl = 300 + Math.floor(Math.random() * 60);   // jitter avoids avalanche
  await redis.set(key, JSON.stringify(row), 'EX', ttl);
  await redis.del(`${key}:lock`);
  return row;
}

// Invalidate on write: delete, do not update
async function updateProduct(id, data) {
  await db.updateProduct(id, data);             // commit first
  await redis.del(`product:v3:${id}`);          // next read repopulates
}
// Idempotent consumer for an at-least-once queue
async function handle(msg) {
  const id = msg.messageId;
  const fresh = await db.insertIfAbsent('processed_messages', id);  // unique key
  if (!fresh) return ack(msg);                  // duplicate: already done
  try {
    await sendInvoice(msg.body);
    await ack(msg);
  } catch (e) {
    await nack(msg);                            // retried; after N tries → DLQ
  }
}
RedisMemcachedCDN edge cache
Data modelStrings, hashes, lists, sets, sorted sets, streamsStrings onlyHTTP responses
PersistenceOptional (RDB/AOF)NoneTransient
ScopeShared across app serversSharedShared, global
Typical latency0.2-1 ms0.2-1 ms10-40 ms (user to edge)
Best forSessions, counters, rate limits, leaderboardsSimple key-value page fragmentsImages, JS, CSS, video
RabbitMQApache KafkaAWS SQS
ModelBroker with exchanges and routingPartitioned append-only logManaged queue
RetentionUntil acknowledgedTime/size based; replayableUp to 14 days
OrderingPer queuePer partitionFIFO queues only
ThroughputTens of thousands/sMillions/sVery high, elastic
Typical useTask queues, RPC, complex routingEvent streaming, analytics, log pipelinesSimple decoupling without ops

Where it is used

Interview questions

Common mistakes

Related topics

System design basics for freshers · System design case studies · Cloud computing basics · AWS core services · REST APIs · Containers: Docker and Kubernetes

Open in the Knowledge reader →Find jobs →