21. How to do LLD (Low-Level Design)

Big picture: If HLD is city planning, LLD is the building blueprint โ€” room layout, plumbing, electrical, load-bearing walls. You zoom into one building (one service) and specify exactly how it works internally.


Learning goals

After this chapter you should be able to:

  • Explain what LLD adds beyond HLD
  • Follow the entities โ†’ schema โ†’ API โ†’ modules โ†’ algorithms pipeline
  • Produce API contracts, table definitions, and module diagrams
  • Write pseudocode for critical algorithms
  • Handle concurrency with constraints, locks, and idempotency keys
  • Deep-dive 1โ€“2 paths in an interview (not every module)
  • Apply this framework to the URL shortener before reading the full case study

Prerequisites: 20-how-to-hld.md, 08-databases.md, 10-caching.md


Everyday analogy: building blueprint

Blueprint elementLLD equivalent
List of rooms (kitchen, bedroom)Entities (User, Url, Click)
Which rooms connectRelationships (User has many Urls)
Pipe diameter, wire gaugeSchema (columns, types, indexes)
Door schedule (swing, lock type)API contracts (endpoints, status codes)
Floor layout zonesModules (Controller โ†’ Service โ†’ Repository)
Elevator capacity algorithmCore algorithms (short code generation, rate limit)
Fire egress planEdge cases & failure handling

An architect doesn't specify HLD city-wide traffic patterns on the blueprint โ€” but the building must fit the city plan. LLD must be consistent with HLD.


What LLD is (and is not)

LLD is

  • Detailed API request/response shapes and error codes
  • Database schema with keys, indexes, constraints
  • Module/class responsibilities inside one service
  • Pseudocode for non-obvious logic
  • Sequence diagrams for tricky flows (redirect, booking seat, idempotent payment)
  • Concurrency strategy (unique constraints, transactions, idempotency)
  • Edge cases (expired URL, duplicate retry, deleted user)

LLD is not

  • Full production code line-by-line
  • Every module detailed (pick 1โ€“2 critical paths)
  • Infrastructure provisioning (Kubernetes node sizes)
  • Re-doing entire HLD from scratch

When asked in interviews: "We agreed on HLD โ€” I'll low-level design the URL Service redirect and create paths."


The LLD pipeline

Work top-down in this order:

Each step constrains the next. Jumping to code before schema leads to rework.


Step 1: Entities

List the nouns in the problem.

URL shortener nouns:

EntityDescription
UserOptional account owner of links
UrlMapping short_code โ†” long_url + metadata
ClickEventSingle redirect event (or aggregated ClickDaily)

Ticket booking nouns: User, Event, Seat, Reservation, Order, Payment.

Chat nouns: User, Conversation, Message, ReadReceipt.

Tip: 3โ€“7 entities is normal for one service. More suggests scope creep.


Step 2: Relationships

Draw cardinality:

User 1 โ”€โ”€โ”€โ”€ * Url        (user may own many links; anonymous urls have null user_id)
Url  1 โ”€โ”€โ”€โ”€ * ClickDaily (aggregated counts per day)
RelationshipImplementation hint
One-to-manyFK on "many" side (urls.user_id)
Many-to-manyJunction table (conversation_participants)
Optional ownershipNullable FK (user_id NULL)

Step 3: Schema / tables

Translate entities to storage. Be explicit about primary keys, indexes, and constraints.

URL shortener schema

-- Core mapping table
CREATE TABLE urls (
  short_code   CHAR(7) PRIMARY KEY,
  long_url     TEXT NOT NULL,
  user_id      BIGINT NULL REFERENCES users(id),
  created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
  expires_at   TIMESTAMPTZ NULL,
  is_active    BOOLEAN NOT NULL DEFAULT true,
  -- optional denormalized fields
  click_count  BIGINT NOT NULL DEFAULT 0  -- or use separate analytics table
);

-- For range queries: "my urls", cleanup job
CREATE INDEX idx_urls_user_created ON urls(user_id, created_at DESC)
  WHERE user_id IS NOT NULL;

-- For expiry sweeper
CREATE INDEX idx_urls_expires ON urls(expires_at)
  WHERE expires_at IS NOT NULL AND is_active = true;

-- Aggregated analytics (async worker writes)
CREATE TABLE clicks_daily (
  short_code   CHAR(7) NOT NULL REFERENCES urls(short_code),
  day          DATE NOT NULL,
  count        BIGINT NOT NULL DEFAULT 0,
  PRIMARY KEY (short_code, day)
);

Why each index exists

IndexQuery it serves
PK on short_codeRedirect lookup by code
idx_urls_user_createdList user's URLs paginated
idx_urls_expiresCron job deactivates expired links

Constraints as correctness tools

ConstraintPrevents
PRIMARY KEY (short_code)Duplicate codes at DB level
NOT NULL long_urlEmpty redirects
REFERENCES users(id)Orphan ownership (optional)
CHECK (length(short_code)=7)Invalid code format (if enforced)

Interview phrase: "Unique constraint on short_code is our last line of defense against collision under concurrent creates."


Step 4: API detailed contracts

Beyond HLD endpoint names โ€” specify JSON, status codes, errors.

POST /api/v1/urls โ€” create

Request:

{
  "long_url": "https://example.com/path?query=1",
  "custom_alias": null,
  "expires_in_days": 365
}

Response 201:

{
  "short_code": "aZ9kQ2x",
  "short_url": "https://go.example/aZ9kQ2x",
  "long_url": "https://example.com/path?query=1",
  "expires_at": "2027-08-06T00:00:00Z"
}

Errors:

CodeWhen
400Invalid URL format, URL too long (> 2048 chars)
409custom_alias already taken
401Auth required but missing (if policy requires login)
429Rate limit exceeded

GET /r/:code โ€” redirect

CodeBody
302Location: {long_url}
404{ "error": "not_found" } โ€” unknown or inactive code
410{ "error": "expired" } โ€” past expires_at

Note: Redirect endpoint often unauthenticated; don't leak existence of private codes via timing attacks in sensitive apps.

GET /api/v1/urls/:code/stats

{
  "short_code": "aZ9kQ2x",
  "total_clicks": 1542,
  "clicks_by_day": [
    { "day": "2026-08-05", "count": 120 },
    { "day": "2026-08-06", "count": 89 }
  ]
}

Step 5: Service modules

Layer responsibilities โ€” names vary by stack (Controller/Handler, Service, Repository).

UrlController     HTTP parsing, status codes, auth middleware
    โ†“
UrlService        business rules: validate URL, create, resolve, deactivate
    โ†“
UrlRepository     SQL queries only
ShortCodeGenerator   collision-resistant code generation
UrlCache          Redis get/set/invalidate
ClickPublisher    enqueue async analytics events

Module rules

LayerMay doMust not
ControllerParse HTTP, call serviceSQL queries
ServiceOrchestrate, business rulesKnow about HTTP status codes deeply
RepositoryCRUD SQLBusiness validation

Step 6: Core algorithms (pseudocode)

Algorithm A: create short URL

function create_url(long_url, user_id?, expires_in_days?):
  if not is_valid_http_url(long_url):
    throw ValidationError

  expires_at = now() + expires_in_days if set else null

  for attempt in 1..MAX_RETRIES:
    code = ShortCodeGenerator.next()   // e.g. 7-char base62

    try:
      db.insert(urls { code, long_url, user_id, expires_at, is_active: true })
      cache.set("url:" + code, long_url, TTL=3600)
      return { short_code: code, short_url: BASE + code }
    catch UniqueViolation:
      continue   // collision โ€” retry with new code

  throw ServiceUnavailable("could not allocate code")

Design choices to mention:

ChoiceAlternativeTrade-off
Random base62Auto-increment ID encodedRandom hides volume; counter is guessable
7 chars (~3.5T space)6 charsShorter URL vs collision risk at scale
Insert-then-cacheCache-then-insertCache only after durable write

Algorithm B: resolve redirect (cache-aside)

function resolve(code):
  if not is_valid_code_format(code):
    return NotFound

  cached = cache.get("url:" + code)
  if cached == EXPIRED_SENTINEL:
    return Gone
  if cached:
    long_url = cached
  else:
    row = db.find_active_by_code(code)
    if row == null:
      return NotFound
    if row.expires_at && row.expires_at < now():
      cache.set("url:" + code, EXPIRED_SENTINEL, TTL=300)
      return Gone
    long_url = row.long_url
    cache.set("url:" + code, long_url, TTL=3600)

  click_publisher.enqueue({ code, ts, ip_hash })   // async, best-effort
  return Redirect(long_url)

Sequence diagram: redirect path


Step 7: Concurrency & correctness

Multiple app instances run simultaneously โ€” LLD must be safe under parallel requests.

Toolbelt

ToolWhen to useURL shortener example
UNIQUE constraintPrevent duplicate rowsshort_code PK
Database transactionMulti-row atomic updateTransfer + ledger (not needed for simple create)
Optimistic lockingConcurrent edits same rowversion column on Url if updates frequent
Pessimistic row lockScarce inventorySELECT FOR UPDATE on seat row (ticket system)
Idempotency keySafe client retriesIdempotency-Key header on POST /urls
Redis SETNXDistributed lock (careful)Optional rate limit counter

Idempotent create example

Client sends: POST /urls  Idempotency-Key: uuid-abc-123

Server:
  if store.contains(uuid-abc-123):
    return cached_response(uuid-abc-123)
  response = create_url(...)
  store.save(uuid-abc-123, response, TTL=24h)
  return response

Duplicate POST due to network retry โ†’ same short URL returned, no double insert.

Cache invalidation on delete

function deactivate(code, user):
  verify ownership
  db.update(urls SET is_active=false WHERE short_code=code)
  cache.delete("url:" + code)

Without delete: stale cache serves redirect for 3600s after user "deleted" link.


Step 8: Edge cases

Brainstorm what breaks at low level:

Edge caseBehavior
Duplicate long URL allowed?Policy: yes (different codes) or no (dedupe) โ€” state assumption
Expired URL410 Gone; optional cache sentinel
Inactive / soft-deleted404 (don't reveal existed)
Malformed code in URL404 early without DB hit
Concurrent create same custom aliasUNIQUE on alias; one wins, one 409
Click queue downRedirect still works; analytics loss acceptable briefly
Long URL > max length400 at validation
Unicode / IDN URLsPunycode normalization before store

Document assumptions in interview:

"I'll allow multiple short links for the same long URL. Expired links return 410."


Class / module sketch (OOP style)

Pseudocode classes โ€” clarity over language:

class UrlService:
  create(long_url, user?, opts?) -> ShortUrlResult
  resolve(code) -> RedirectResult
  deactivate(code, user) -> void
  get_stats(code, user) -> Stats

class ShortCodeGenerator:
  next_code() -> str   // thread-safe or stateless random

class UrlRepository:
  insert(url: UrlEntity) -> void   // throws on unique violation
  find_active_by_code(code) -> UrlEntity?
  deactivate(code) -> bool

class UrlCache:
  get(code) -> str?
  set(code, long_url, ttl_sec)
  delete(code)

class ClickPublisher:
  publish(event: ClickEvent) -> void   // fire-and-forget to queue

Functional/module style is equally valid โ€” match your interview language.


LLD depth guidance for interviews

You cannot detail every module in 45 minutes. Pick 1โ€“2 critical paths.

SystemDeep-dive paths
URL shortenerCode generation + collision; redirect cache-aside
Ticket bookingSeat hold with TTL; SELECT FOR UPDATE
ChatMessage insert + fanout to online recipients
Rate limiterToken bucket in Redis with Lua atomicity
PaymentIdempotency key + webhook retry handling

Script:

"At HLD we have URL Service, Redis, Postgres, queue. I'll LLD the create and redirect flows โ€” they're the correctness and performance core."

Spend ~15โ€“20 min here; leave admin APIs as "similar CRUD."


HLD โ†’ LLD mapping (URL shortener)

HLD boxLLD artifacts produced
URL ServiceModules, APIs, algorithms above
Postgresurls, clicks_daily schema
RedisKey pattern url:{code}, TTL policy
QueueClickEvent payload schema, idempotent consumer
Load Balancer(Usually no LLD โ€” infra)

Async consumer LLD (click worker)

function process_click_event(event):
  // idempotent: at-least-once delivery from SQS
  if dedup_store.seen(event.event_id):
    return

  db.execute("""
    INSERT INTO clicks_daily (short_code, day, count)
    VALUES (?, ?, 1)
    ON CONFLICT (short_code, day)
    DO UPDATE SET count = clicks_daily.count + 1
  """, event.code, event.day)

  dedup_store.mark_seen(event.event_id, TTL=7d)

Common LLD mistakes

MistakeFix
Schema with no indexes for hot queriesIndex redirect lookup path
Cache before DB writeWrite DB first, then cache
No unique constraint on short_codeDB enforces under concurrent creates
God class doing everythingLayer controller / service / repository
Ignoring idempotencyAt-least-once queues duplicate work
Over-design every endpointDeep-dive 1โ€“2 paths only
LLD inconsistent with HLD"We said Redis cache-aside" โ€” show key names

Bridging to Part 2: case studies

Every case study in Part 2 follows:

1. Requirements & estimates
2. HLD  (chapter 14 checklist)
3. LLD  (this chapter's pipeline)
4. Scale evolution
5. Recap & interview Q&A

Recommended next step

You've learned HLD and LLD process. Apply both to:

โ†’ Case Study 01: URL Shortener

Read it after attempting your own design. Compare:

  • Did you cache the redirect path?
  • Did you async the click counter?
  • Is your schema close?

Then continue through case studies 02โ€“10 for spaced practice.


Check your understanding (Q&A)

1. Name three artifacts an LLD should produce.

Answer

Detailed API contracts (request/response/errors), database schema (tables, indexes, constraints), and module structure with algorithms in pseudocode. Sequence diagrams and edge-case lists are also common artifacts.

2. Why are unique constraints part of LLD, not only application code?

Answer

Multiple app instances can race on the same insert. Application-level checks alone can't guarantee uniqueness under concurrency. A database UNIQUE constraint (or PK) enforces correctness even if two servers generate the same code simultaneously.

3. What should you deep-dive for a ticket booking system?

Answer

Seat reservation concurrency: holding a seat with TTL, SELECT FOR UPDATE or optimistic locking, preventing double-booking when two users checkout the same seat, and releasing holds on payment timeout.

4. What's the cache-aside pattern for redirect?

Answer

On read: check cache first. On miss: read DB, populate cache with TTL, return result. On write/create: write DB, then set cache. On delete: invalidate cache key. App code orchestrates โ€” cache isn't the source of truth.

5. Why enqueue click tracking instead of synchronous DB increment?

Answer

Redirect is the hot path โ€” users wait for 302. Synchronous increment adds DB write latency to every redirect. Async queue decouples analytics; brief analytics loss during outage is acceptable if redirects still work.

6. How does idempotency key help POST /urls?

Answer

Client retries duplicate POSTs on timeout. Server stores Idempotency-Key โ†’ response mapping. Second request with same key returns original response without creating a second short URL.

7. Entity โ†’ schema โ†’ API โ€” why this order?

Answer

Entities define what exists. Schema defines persistent shape. API defines external interface over that data. Modules and algorithms implement API using schema. Skipping early steps causes APIs that don't fit the data model.

8. When would you use optimistic vs pessimistic locking?

Answer

Optimistic (version column): low contention, read-heavy, conflicts rare โ€” retry on version mismatch. Pessimistic (SELECT FOR UPDATE): high contention scarce resources (last seat) โ€” lock row during transaction to prevent others booking.


Quick reference card

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  LLD PIPELINE:                                                  โ”‚
โ”‚    Entities โ†’ Relationships โ†’ Schema โ†’ API โ†’ Modules          โ”‚
โ”‚    โ†’ Algorithms โ†’ Concurrency โ†’ Edge cases                      โ”‚
โ”‚  DEEP-DIVE: 1โ€“2 critical paths (redirect, booking, payment)   โ”‚
โ”‚  CORRECTNESS: UNIQUE constraints, transactions, idempotency     โ”‚
โ”‚  CACHE: write DB first; invalidate on delete                    โ”‚
โ”‚  ASYNC: hot path stays lean; queue for side effects             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Next: Before binge-reading solutions, learn the method โ†’ The Thinking Loop

Then drill Part 2 โ†’ Case Study 01: URL Shortener