Skip to main content

One-Page Cheat Sheet

How to use this page

Read it the night before and again 30 minutes before the interview. Every number here is approximate — say "roughly" when you quote one, and know which page explains it.

TL;DR​

  • Memory ≈ 100 ns, SSD read ≈ 100 µs, same-DC round trip ≈ 0.5 ms, cross-region ≈ tens to 100+ ms.
  • 1 day ≈ 10^5 s, so 1M/day ≈ 12/s and 100M/day ≈ 1,200/s; plan peaks at 2–3× (normal) or 10×+ (sales).
  • 99.9% ≈ 43 min/month down, 99.99% ≈ 4.3 min/month. Serial dependencies multiply availabilities.
  • Default answers: Postgres for money, Redis for hot reads/counters, Kafka for events with replay, object storage for blobs, a search engine for text, OLAP for analytics.
  • At-least-once delivery + idempotent consumers is the realistic "exactly-once".
  • Money: integers or decimals (never float), currency with every amount, double-entry, immutable entries, idempotency keys, daily reconciliation.

Latency numbers (rough)​

OperationRough timeRemember as
L1 cache reference≈ 1 ns
Branch mispredict≈ 3–5 ns
L2 cache reference≈ 4 ns
Uncontended mutex lock/unlock≈ 15–25 ns
Main memory reference≈ 100 ns100× L1
Compress 1 KB with a fast codec≈ 1–3 µs
Read 1 MB sequentially from memory≈ tens of µs
NVMe SSD random 4 KB read≈ 20–100 µs≈ 1,000× memory
Read 1 MB sequentially from NVMe SSD≈ 0.2–1 ms1–5 GB/s
Round trip within one data centre / AZ≈ 0.1–0.5 ms
Redis GET, same DC≈ 0.2–1 msnetwork dominates
PostgreSQL primary-key lookup, same DC≈ 0.5–2 ms
Cross-AZ round trip≈ 1–2 ms
Kafka produce with acks=all, same region≈ 2–10 ms
HDD seek / read 1 MB sequentially≈ 5–10 ms eachavoid on hot paths
Ho Chi Minh City ↔ Hanoi round trip≈ 15–30 ms
Vietnam ↔ Singapore round trip≈ 20–50 mscommon cloud region
Asia ↔ US round trip≈ 150–250 ms

Consequences: a request with 10 sequential DB calls costs ≈ 10 ms of network alone; a synchronous cross-region call in a payment path eats most of a 200 ms budget; anything on disk per request needs caching or batching.

Availability nines​

AvailabilityPer yearPer 30-day monthPer weekPer day
99%3.65 days7.2 h1.68 h14.4 min
99.9%8.76 h43.2 min10.1 min1.44 min
99.95%4.38 h21.6 min5.04 min43.2 s
99.99%52.6 min4.32 min1.01 min8.64 s
99.999%5.26 min25.9 s6.05 s0.86 s
  • Serial (all must work): A = A1 × A2 × … → three services at 99.9% ≈ 99.7%.
  • Parallel redundancy (any one works): A = 1 − (1 − A1)(1 − A2) → two independent 99% replicas ≈ 99.99%. Real failures are correlated (same AZ, same bug, same config push), so the real number is lower.
  • RTO = how long to recover; RPO = how much data you may lose. Synchronous replication → RPO ≈ 0 at a latency cost. See High Availability & DR and Observability & SLOs.

Estimation shortcuts​

FactValue
Seconds per day86,400 ≈ 10^5 (use 100k, correct by ≈ 15%)
Seconds per month / year≈ 2.6M / ≈ 31.5M
1M per day≈ 12 per second
10M / 100M / 1B per day≈ 115 / 1,160 / 11,600 per second
Peak factor2–3× normal; 10×+ for flash sales, campaigns, payday
2^10 / 2^20 / 2^30 / 2^40≈ 10^3 (K) / 10^6 (M) / 10^9 (G) / 10^12 (T)
int64, timestamp8 B each
UUID16 B binary, 36 chars as text
Typical JSON event / API response≈ 0.5–2 KB
Product thumbnail / photo≈ 20–50 KB / ≈ 0.5–3 MB
Replication factor3 (plan raw storage × 3)
QPS = requests per day / 86,400 (x peak factor)
Storage = items per day x item size x retention days x replication
Bandwidth = QPS x payload size
Cache size = hot items x item size (often 10-20% of daily working set)
Concurrency = throughput x latency (Little's law)
e.g. 2,000 req/s x 0.15 s = 300 requests in flight -> pool sizes
Servers = peak QPS / per-server QPS (measured, keep 30-50% headroom)

Very rough single-node ceilings to sanity-check (measure your own): a stateless Go API node handles thousands to tens of thousands of simple requests/s; a tuned PostgreSQL primary handles thousands to low tens of thousands of simple writes/s; a Redis node ≈ 100k+ simple ops/s; a Kafka partition ≈ tens of MB/s. See Back-of-the-Envelope Estimation.

Pattern → problem map​

ProblemPatternRead
Client retries cause duplicatesIdempotency key + unique constraint / dedup storeIdempotency
Write DB and publish event atomicallyTransactional outbox or CDCOutbox & CDC
Business transaction across servicesSaga (orchestrated or choreographed), TCCDistributed Transactions
Read-heavy hot dataCache-aside + TTL + stampede protectionCaching
One key or account is extremely hotLocal cache, key replication, sharded counters, pull modelNews Feed
Traffic spike beyond capacityQueue-based load levelling, waiting room, rate limiting, load sheddingFlash Sale
Slow or failing dependencyTimeout + retry with jitter + circuit breaker + bulkheadResilience Patterns
Oversell on limited stockAtomic conditional decrement, reservation with TTLInventory & Flash Sales
Lost update on one rowAtomic UPDATE, optimistic version, SELECT FOR UPDATELocking & Concurrency
Per-entity orderingPartition by entity key (Kafka key, shard key)Message Queues
Single writer / leaderLease with fencing token, consensus store (etcd)Distributed Locks
Read model differs from write modelCQRS with projectionsEvent-Driven Architecture
Full history and auditAppend-only ledger, event sourcing, audit logLedger Design
Huge, growing tableTime partitioning, archival, shardingPartitioning in Practice
Full-text search, facetsInverted index fed by CDC/eventsSearch Systems
Replace a legacy systemStrangler fig + anti-corruption layer + reconciliationMigration Strategies
Long-running business processExplicit state machine + durable workflow/timersOrder Management
Unknown outcome after timeoutStatus query + reconciliation, never assume failureReconciliation

Database choice matrix​

NeedChooseExamplesAvoid when
ACID, relations, money, ad-hoc queriesRelationalPostgreSQL, MySQL, OracleWrite volume beyond one primary with no natural shard key
Huge write throughput, key-based access, multi-DCWide-column / managed KVCassandra, ScyllaDB, DynamoDBYou need joins, ad-hoc queries or multi-row transactions
Flexible documents read as a wholeDocumentMongoDB, CouchbaseHeavy cross-document invariants
Sub-ms reads, counters, rate limits, leaderboardsIn-memory KVRedis, Valkey, MemcachedIt would be the only copy of important data
Full-text search, facets, relevanceSearch engineElasticsearch, OpenSearchAs the system of record
Analytics over billions of rowsColumnar OLAPClickHouse, BigQuery, DruidPoint lookups and frequent updates
Metrics over timeTime-seriesPrometheus, TimescaleDBBusiness entities
Relationship traversal (fraud rings)GraphNeo4j, NeptuneSimple one-hop lookups
Files, images, statements, backupsObject storageS3, GCS, MinIOSmall, frequently updated records
Strong consistency with horizontal scaleDistributed SQLSpanner, CockroachDB, TiDB, YugabyteDBTeam lacks operational experience; latency budget is tight

See NoSQL Data Modeling and Storage Engines.

Consistency choices​

ModelGuaranteeUse forCost
Linearizable (strong)Every read sees the latest committed writeBalance checks, stock decrement, uniquenessLatency; unavailable under partition (CP)
Serializable transactionsTransactions behave as if run one at a timeTransfers, double-booking preventionThroughput, retries on conflict
Read-your-writesA user sees their own updatesProfile edits, "my orders" after checkoutSticky sessions or primary reads
Monotonic readsNo going back in time between readsPaging through history on replicasSession pinning
CausalEffects seen after causesChat replies, comment threadsTracking dependencies
EventualReplicas converge eventuallyFeeds, counters, search index, analyticsStale reads, conflict resolution

See Consistency Models and CAP & PACELC.

Caching strategies​

StrategyHowStrengthsWeaknessesUse for
Cache-asideApp reads cache, on miss loads DB and fillsSimple, cache failure toleratedStale until TTL/invalidation; stampedesDefault for read-heavy data
Read-throughCache library loads from DB on missCleaner app codeSame staleness; library couplingUniform entity caches
Write-throughWrite cache and DB togetherCache always warmWrite latency; caches cold dataRead-after-write heavy data
Write-behindWrite cache, flush to DB asyncFast writes, batchingData loss on cache failureCounters, views — never money
Refresh-aheadRefresh hot keys before expiryNo miss latency on hot keysWasted refreshesPredictable hot sets (home page)

Invalidation: delete on write (don't update), short TTLs as a safety net, versioned keys for bulk changes, CDC-driven invalidation for many writers. Stampedes: singleflight, per-key lock, early probabilistic expiry, serve-stale-while-revalidate. Never use a cache to authorise money movement — check balances and stock at the source.

Messaging semantics​

SemanticsHowRiskUse for
At-most-onceCommit/ack before processing; fire-and-forgetLossMetrics, typing indicators, best-effort analytics
At-least-onceProcess, then commit/ack; retry on failureDuplicatesAlmost all business events — with idempotent consumers
Effectively-onceIdempotent producer + transactions (Kafka) inside the pipeline, or at-least-once + dedup at the sinkComplexity; boundary ends at external systemsLedger postings, financial aggregates
  • Ordering is guaranteed only per partition / per key. Choose the key (account ID, order ID) deliberately.
  • Plan for poison messages (DLQ after N attempts), consumer lag alerts, retention for replay, and schema evolution (registry, backward-compatible changes).
KafkaRabbitMQSQS
ModelPartitioned log, consumers track offsetsBroker queues, routing via exchangesManaged queue
ReplayYes, within retentionNo (once acked)No
OrderingPer partitionPer queue (single consumer)FIFO queues only
StrengthThroughput, replay, stream processingFlexible routing, per-message TTL/priorityZero ops

Money handling rules​

  1. Never use floating point. Use integer minor units (int64) or fixed-precision decimals (NUMERIC(19,4)); in Go, int64 or a decimal library.
  2. Store the currency with every amount (ISO 4217). VND has 0 minor units in ISO 4217, USD 2, KWD 3 — don't hard-code 2.
  3. Round once, by a stated rule (half-up vs banker's rounding), at a defined step; allocate remainders explicitly (100,000₫ split three ways = 33,334 + 33,333 + 33,333).
  4. Double-entry: every movement has debits equal to credits; balances derive from entries.
  5. Immutable entries: correct with reversal/adjustment entries, never UPDATE/DELETE.
  6. Idempotency on every money-moving call, with a unique constraint on the business reference.
  7. A timeout is "unknown", not "failed". Query status, then reconcile; never blindly retry a payout.
  8. Reconcile with every external party (switch, PSP, partner bank) daily and ideally intraday.
  9. Holds vs postings: authorisation reserves (available balance), capture/settlement posts (ledger balance).
  10. Time: store UTC, display Asia/Ho_Chi_Minh; business date and cut-off times differ from calendar date.
  11. Audit: who, what, when, why for every change; four-eyes approval for manual adjustments.
  12. FX: store rate, source and timestamp with each conversion.

See Double-Entry Ledger Design and Schema Patterns: Money, Audit, Multi-tenancy.

LLM feature design checklist​

  1. Does it need an LLM? Rules, search or a form may be cheaper, faster and auditable.
  2. Non-AI fallback. The feature degrades; checkout, payments and transfers never depend on a model call.
  3. Facts from systems of record, not from the model or stale documents: rates, fees, balances, stock come from tools/APIs, cited and timestamped.
  4. Retrieval respects entitlements: filter by the caller's ACL before ranking, never after generation.
  5. Untrusted text is data, not instructions: memos, reviews, emails, tickets, web pages. Break the lethal trifecta (private data + untrusted input + a way out).
  6. Side effects are proposals: the model drafts, the user confirms (strong authentication for money); tools are narrow, scoped to the user, idempotent.
  7. Structured output validated against a schema; bounded retries; never execute or render raw output.
  8. Gateway: timeouts, fallback on retryable errors only, per-tenant token budgets, cost attribution, PII redaction.
  9. Evals as a release gate: golden set + red-team set; re-run on every prompt, model or retrieval change.
  10. Trace and audit every step (prompt/model version, retrieved docs, tool calls) without logging card data or secrets.

See LLM Application Architecture and LLM Security, Privacy & Governance.

Reference diagrams​

1. Baseline scalable service

2. Outbox + CDC event flow

3. Checkout saga (orchestrated)

4. Multi-region active-passive

5. Admission control for a traffic spike

Self-check​

1. A request makes 8 sequential calls to a database in another AZ. Rough network cost?

≈ 1–2 ms per cross-AZ round trip × 8 ≈ 8–16 ms before any query time. Fix with batching, fewer round trips, or co-locating the service with the primary.

2. Three serial services at 99.95% each, behind a load balancer at 99.99%. Overall availability?

0.9995³ × 0.9999 ≈ 0.9984 → ≈ 99.84%, or roughly 70 minutes of downtime per month. Serial dependencies erode availability quickly — hence caching, async paths and graceful degradation.

3. 30M orders/day, 2 KB each, kept 5 years with 3× replication. Storage?

30M × 2 KB = 60 GB/day; × 365 × 5 ≈ 110 TB; × 3 ≈ 330 TB. The order of magnitude says time partitioning plus archival of old orders to cheaper storage.

🧠 Flashcards0/10 learned · 0 retries
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).