Skip to the content

Lesson 240 of 296

Design: rate limiter and notification system

What you will learn

  • Designing a rate limiting service used by many APIs
  • Designing a notification system for email, SMS and push
  • Templates, preferences, retries and deduplication
On this page

Part A: a rate limiter service

Requirements: limit API requests per client key (API key, user, IP) using rules such as "100 requests per minute per API key; 5 login attempts per 15 minutes per account". Low added latency (a few milliseconds). Shared across all API servers. Configurable rules. Clear responses (429 and headers).

Where it lives:

OptionNotes
In an API gateway or edge (AWS API Gateway usage plans, Cloudflare, Kong, Envoy)No application code; per-key limits; less business context
Middleware in each service calling RedisMost flexible; per-tenant and per-plan rules
A separate rate limiting serviceCentral rules for many services; adds a network hop

Design:

Client → Load balancer → API server [rate limit middleware] ──→ Redis (counters / buckets)
                                         ↑ rules (cached in memory, loaded from a config store)
  1. The middleware identifies the client key and the matching rule.
  2. It runs one atomic operation in Redis (a Lua script implementing a token bucket or sliding window, Lesson 238).
  3. Allowed: continue, with RateLimit-Remaining headers. Denied: 429 with Retry-After.

Deep dives:

  • Atomicity: read-modify-write in separate commands races between servers; use Lua scripts or INCR (which is atomic).
  • Redis down: decide fail open (allow requests, risk overload) or fail closed (reject, risk blocking legitimate users). Most public APIs fail open with a local in-memory fallback limit; security-critical limits (login) may fail closed.
  • Latency: Redis in the same region and availability zone; pipeline commands; optionally a small local allowance per server that syncs periodically (less exact, faster).
  • Hot keys: a single huge customer's key can be split across several Redis keys.
  • Multi-region: limits per region, or accept approximate global limits.
  • Observability: log and count rejections per rule, to tune limits and detect attacks.

Part B: a notification system

Requirements: services send notifications to users by email, SMS and mobile push (and in-app). Support templates, user preferences (opt-outs, quiet hours), high volume (marketing campaigns to millions), reliable delivery with retries, no duplicates, delivery tracking.

Estimates (example): 10 million notifications a day is about 115 per second on average, but campaigns create huge bursts: a queue is essential.

High-level design:

Services ─→ Notification API ─→ [validate, check preferences, render template, dedupe]
                                   ─→ queue per channel: email | sms | push
                                          ↓              ↓       ↓
                                     Email workers   SMS workers  Push workers
                                          ↓              ↓       ↓
                                   SES / SendGrid    Twilio    APNs / FCM
                                          ↓
                               Delivery status (webhooks) → notifications log

Components:

  • Notification API: receives { userId, type: "order_shipped", data: {...}, idempotencyKey }. Returns 202 quickly.
  • Preferences service: which channels the user allows for each type; unsubscribes (required by law for marketing in the UK under PECR); quiet hours and time zones.
  • Templates: stored per type, channel and language, filled with data (and escaped to prevent injection into HTML emails).
  • Contact info: email addresses, phone numbers, device tokens (a user can have several devices; remove tokens the push provider reports as invalid).
  • Queues per channel: each channel has different speed and limits; a slow SMS provider must not delay emails (a bulkhead, Lesson 238).
  • Workers: call third-party providers, respecting their rate limits, with retries, backoff and dead-letter queues (Lesson 204).
  • Delivery tracking: providers send webhooks (delivered, bounced, opened, complained); store statuses; stop emailing addresses that hard-bounce or complain (protects your sender reputation).

Deep dives:

  • No duplicates: an idempotency key per notification (for example order_shipped:order_101:user_1), checked atomically before sending (Lesson 195). Queues are at-least-once, so workers check "already sent?" too.
  • Priorities: separate queues for urgent transactional messages (password reset, two-factor codes) and bulk marketing, so a campaign never delays a login code.
  • Reliability: if the email provider is down, retry with backoff; consider a secondary provider with failover.
  • Scheduling: "send at 9 a.m. in each user's time zone": a scheduler that enqueues at the right moments.
  • Cost: SMS is expensive; prefer push or email where the user allows.

How to say it in an interview

"For a rate limiter I put middleware in the services, or use the API gateway, calling Redis with atomic Lua scripts for a token bucket or sliding window, rules cached in memory, 429 with Retry-After on rejection, and a clear fail-open or fail-closed decision if Redis is unavailable. For notifications I accept requests on an API that returns 202, check preferences and render templates, then put messages on separate queues per channel and priority, with workers that respect provider limits, retry with backoff, use dead-letter queues, and de-duplicate with idempotency keys. Provider webhooks update delivery status, and bounces and unsubscribes feed back into preferences."

Key words

WordMeaning
API gatewayA front door handling routing, auth and rate limits for APIs
Fail open / fail closedAllow / reject requests when a safety system fails
Lua script (Redis)Code run atomically inside Redis
Transactional vs marketing messageTriggered by a user's action vs promotional
Push notificationA message to a mobile device via APNs (Apple) or FCM (Google)
BounceAn email that could not be delivered

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.