PE·186
Technical Trade-offs
Making engineering decisions in product context: how to reason about trade-offs (forces, reversibility, one-way and two-way doors, cost of delay, option value), decision matrices with weights and a sensitivity check computed in Python, architecture decision records, then the ten trade-offs the roadmap names, each with forces, decision criteria, a TiffinBox decision and its failure modes: simple vs flexible, fast vs maintainable (technical debt and its interest), strong consistency vs availability (CAP and PACELC in product terms), cost vs performance (with a cost model), build vs buy (total cost of ownership), monolith vs microservices, synchronous vs asynchronous (with queueing arithmetic), SQL vs NoSQL by access patterns, self-hosted model vs API (a break-even calculation), and local vs distributed state, closing with how to communicate trade-offs to non-engineers.
Start here: every choice costs something
A technical trade-off is a decision where improving one quality makes another worse: faster but less durable, simpler but less flexible, cheaper but slower, consistent but less available. There's rarely a "best" option, only a best fit for this context. Good engineers make the trade-off explicit, measure it where they can, and write it down.
Three trade-offs the lab measured on real software
Send the confirmation email now, or later? Calling the email provider inside the "skip" request made the request as slow and unreliable as the provider: median 300 ms, worst 1% 3 seconds, and 3 of 200 requests failed because the provider did. Putting the email on a queue (Redis) made the request take 0.1 ms and never fail, at the price of a worker to run, retries to design, and emails that arrive later (with one worker, the last of a 200-request burst went out 110 s later).
Confirm a write instantly, or only when it's safely on disk? PostgreSQL with synchronous_commit=off committed 3× faster (0.06 ms vs 0.19 ms), and in a crash could lose the last ~200 ms of writes that users had been told were saved. Fine for analytics events; not for payments.
Tables or documents? Storing orders as JSON documents made "fetch one order" simple and fast, but finding all orders with a dish took 5× longer and renaming a dish everywhere 3× longer than with normalised tables.
Writing it down: an ADR
An architecture decision record is a one-page note: context (what forces are at play), decision (what we chose), consequences (what gets better, what gets worse, what we'll watch). Six months later it answers "why on earth did we do this?" and tells you when the decision should be revisited.
How deep to go in technical trade-offs
Volume 17 defines six mastery levels; for trade-offs they look like this:
| Level | You can… |
|---|---|
| L1 | name common trade-offs and the qualities they exchange |
| L2 | write an ADR for a decision in your team |
| L3 | analyse a decision's forces and measure the key trade-off with a prototype or benchmark |
| L4 | recognise when an old decision's context has changed and revisit it |
| L5 | make and communicate architecture-level trade-offs across teams and stakeholders |
| L6 | set decision-making practice: ADR culture, review forums, reversibility thinking |
How to think about trade-offs
Every engineering choice buys something with something else. "It depends" is the start of an answer; a good answer says on what, and makes the choice explicit, justified and revisitable.
The questions
- What problem and outcome? (chapter 181) A trade-off only makes sense relative to goals.
- What are the forces? Requirements and NFRs (chapter 185), constraints, team skills, time, money, risk, regulation.
- What are the options? At least three, including "do nothing" and "the simplest thing that could work".
- How reversible is each? Cheap to undo, or a one-way door?
- What's the cost of delay? Waiting to learn more vs deciding now.
- How will we know if we were wrong? Signals, thresholds, a review date.
One-way and two-way doors
Jeff Bezos's framing: two-way doors (reversible decisions: a UI change behind a flag, a library choice inside one service) should be made quickly by small teams; one-way doors (irreversible or very expensive to reverse: a public API contract, a database for core data, a vendor contract with lock-in, deleting data) deserve careful analysis. Many decisions can be made more reversible: abstractions at seams, feature flags, data export paths, contracts with exit clauses, dual-writes during migrations.
Decision matrices
When options differ on several criteria, a weighted decision matrix makes the reasoning visible. Then check sensitivity: does the winner change if the weights change a little? If yes, the decision hinges on that weight, so discuss it explicitly.
import numpy as np, itertools
criteria = {"time_to_market": 0.30, "operating_cost": 0.20, "reliability": 0.25, "team_familiarity": 0.15, "lock_in": 0.10}
options = { # scores 1–5 (higher is better; for lock_in, 5 = least lock-in)
"Managed Postgres": {"time_to_market": 4, "operating_cost": 3, "reliability": 5, "team_familiarity": 5, "lock_in": 4},
"Self-hosted Postgres (k8s)":{"time_to_market": 2, "operating_cost": 4, "reliability": 3, "team_familiarity": 3, "lock_in": 5},
"Managed DynamoDB": {"time_to_market": 4, "operating_cost": 4, "reliability": 5, "team_familiarity": 2, "lock_in": 1},
}
def total(opt, w): return sum(w[c] * opt[c] for c in w)
scores = {name: round(total(o, criteria), 2) for name, o in options.items()}
scores # {'Managed Postgres': 4.2, 'Self-hosted Postgres (k8s)': 3.1, 'Managed DynamoDB': 3.65}
# Sensitivity: perturb each weight by ±0.1 (renormalised) and see whether the winner changes
winner = max(scores, key=scores.get); flips = []
for c, delta in itertools.product(criteria, (-0.1, 0.1)):
w = dict(criteria); w[c] = max(0.0, w[c] + delta); s = sum(w.values()); w = {k: v / s for k, v in w.items()}
new = max(options, key=lambda n: total(options[n], w))
if new != winner: flips.append((c, delta, new))
winner, flips # ('Managed Postgres', []): no single ±0.1 weight change flips it
Matrices structure the discussion; they don't make the decision. Scores encode judgement, so document why each score was given.
Architecture decision records
An ADR (Michael Nygard's format) records one significant decision: context, decision, consequences. Keep them in the repository next to the code, numbered and immutable (supersede rather than edit).
# ADR 0012: Store meal credits in the subscription service's Postgres, not a separate ledger service
Status: Accepted (2026-10-20) · Deciders: scheduling team, payments lead · Supersedes: none
## Context
Skips create meal credits (chapter 181). Credits affect billing and are a financial liability.
Volumes: ~4k skips/day, ~50k subscribers. Two engineers, six-week appetite.
Options considered: (1) credits table in the subscription DB, (2) new ledger microservice,
(3) payment provider's customer-balance feature.
## Decision
Option 1: an append-only `credit_entries` table (double-entry style: +1 on skip, −1 on use/expiry)
in the existing subscription Postgres, updated in the same transaction as the delivery state change.
## Consequences
+ Atomic skip + credit (no distributed transaction); fastest to ship; team knows Postgres.
+ Auditable, append-only entries; balances derived by SUM and cached.
− Finance reporting must read from the subscription DB (via CDC to the warehouse).
− If other products need credits, we'll extract a ledger service; the append-only model eases that.
Review trigger: > 3 services needing credits, or > 1M entries/day.
1. Simple vs flexible
| Simple | Flexible |
|---|---|
| Solves today's known problem directly | Anticipates variation (plugins, configuration, generic abstractions) |
| Easy to read, test, change | Handles future cases without code changes |
| Risk: rework when needs change | Risk: complexity for needs that never arrive (YAGNI), harder to understand |
Decide by: evidence of variation (do we already have two or three concrete cases?), cost of change later (is the code isolated behind a seam?), and who will maintain it. The rule of three: generalise when the third real instance appears. Flexibility is cheapest when it's data or configuration for known dimensions of change (TiffinBox's cut-off time and holiday calendar per city: configurable, because a second city is planned) rather than speculative frameworks.
TiffinBox: the skip rule is a small function with the cut-off and calendars as configuration; no "rules engine" until rules multiply.
2. Fast vs maintainable
Shipping fast and keeping code healthy are not opposites in the long run (DORA's research shows high performers achieve both), but under a deadline they trade off.
Technical debt (Ward Cunningham's metaphor): taking a shortcut now is borrowing; every later change pays interest in extra effort until the debt is repaid. Martin Fowler's debt quadrant distinguishes deliberate vs inadvertent and prudent vs reckless debt: "we must ship before the festival; we'll hard-code the cut-off and fix it in November" is deliberate and prudent; "what's a transaction?" is inadvertent and reckless.
Managing it:
- Take debt deliberately, write it down (a ticket with the interest you expect), and agree on a repayment trigger.
- Pay down debt where you change code often (high interest); leave stable, ugly code alone (low interest).
- Protect the seams even when cutting corners inside them: clean interfaces, tests on the contract.
- Make quality cheap: automated tests, linters, CI, small changes (Volume 8, 11).
- A throwaway prototype is fine if it's truly thrown away; the classic failure is a prototype becoming production.
def debt_cost(shortcut_saves_days, extra_days_per_change, changes_per_month, months):
interest = extra_days_per_change * changes_per_month * months
return {"saved_now": shortcut_saves_days, "interest_paid": interest, "net": shortcut_saves_days - interest}
debt_cost(10, 0.5, 6, 3) # saves 10 days now, costs 9 over 3 months: barely worth it
debt_cost(10, 0.5, 6, 12) # costs 36 over a year: repay early if this code keeps changing
3. Strong consistency vs availability
The CAP theorem (Volume 5): during a network partition, a distributed data system must choose between consistency (every read sees the latest write, or fails) and availability (every request gets a response, possibly stale). PACELC adds: Else, in normal operation, the trade-off is latency vs consistency (synchronous replication across regions adds latency).
Product framing: what's the cost of a stale or conflicting answer, versus the cost of an error or a slow response?
| Data | Choice | Why |
|---|---|---|
| Meal credits and payments | Strong consistency (single primary, transactions) | Double credits or double charges are real money and trust |
| Delivery tracking map | Availability, eventual consistency | A position a few seconds old is fine; an error page is not |
| Menu and ratings | Eventual, cached | Staleness of minutes is harmless |
| Skip near the cut-off | Strong, with a clear rejection if the system can't confirm | Better "try again" than a skip the kitchen never sees |
Techniques that soften the trade-off: read-your-writes consistency for the acting user, idempotent operations with retries, conflict-free data types for collaborative state, and clear UI states ("syncing…").
4. Cost vs performance
Faster usually costs more: bigger instances, more replicas, caches, multi-region, premium networks, larger models. The question is what performance is worth in product terms (chapter 183): conversion, retention, SLA penalties, user satisfaction, and where users actually feel it.
- Optimise the user-visible percentile that matters (p95 of the skip API during the cut-off rush), not averages, and not everything.
- Know the cost per unit (per request, per meal, per active user) and its trend.
- Prefer efficiency before capacity: fix N+1 queries, add indexes, cache, batch, compress, before buying hardware.
- Elasticity: autoscale for peaks (06:30–07:00 skip rush, 12:00–13:00 delivery tracking) instead of provisioning for peak all day.
def monthly_cost(baseline_instances, peak_instances, peak_hours_per_day, price_per_hour=0.17, autoscale=True):
hours = 30 * 24
if not autoscale:
return round(peak_instances * hours * price_per_hour)
return round((baseline_instances * hours + (peak_instances - baseline_instances) * peak_hours_per_day * 30) * price_per_hour)
monthly_cost(3, 12, 2.5, autoscale=False), monthly_cost(3, 12, 2.5) # $1,469 vs $482: ~3× difference
5. Build vs buy
| Build | Buy (SaaS, managed service, open source with support) |
|---|---|
| Fits exactly; differentiating capability; full control | Faster; vendor handles operations, security, compliance |
| Ongoing cost: engineers to build and maintain forever | Subscription cost; integration effort; lock-in; less control |
Decide by:
- Is it core to how we win? Build what differentiates (TiffinBox's delivery batching and kitchen planning); buy commodities (payments, SMS, email, authentication, observability, feature flags).
- Total cost of ownership over 3 years, including maintenance, on-call, security patching and opportunity cost of the team's time.
- Lock-in and exit cost: data export, standard protocols, contract terms.
- Compliance and data residency: can the vendor meet them?
- Maturity and risk: vendor stability, SLAs, support.
def tco_build(eng_months_build, eng_months_maintain_per_year, eng_month_cost=250_000, infra_per_month=15_000, years=3):
return eng_months_build * eng_month_cost + years * (eng_months_maintain_per_year * eng_month_cost + 12 * infra_per_month)
def tco_buy(subscription_per_month, integration_eng_months, eng_month_cost=250_000, years=3, growth_per_year=0.3):
subs = sum(subscription_per_month * 12 * (1 + growth_per_year) ** y for y in range(years))
return integration_eng_months * eng_month_cost + subs
# Feature flags & experimentation (₹): build in-house vs buy a platform
build, buy = tco_build(4, 2), tco_buy(60_000, 0.5)
round(build / 1e5, 1), round(buy / 1e5, 1) # ≈ 30.4 vs 30.0 lakh over 3 years: a tie on cost,
# so time to market (weeks vs months) and team focus decide → buy, unless experimentation is your edge
6. Monolith vs microservices
Covered in depth in Volume 13 (chapters 139–141). The product-level summary:
| Modular monolith | Microservices |
|---|---|
| One deployable; in-process calls; one database (with module boundaries) | Independent deployables owning their data; network calls |
| Simple operations, transactions, debugging, refactoring | Independent scaling, deployment and team autonomy at scale |
| Risk: modules erode into a big ball of mud | Risk: distributed-systems complexity, data consistency, operational cost |
Decide by team size and structure (Conway's law), need for independent scaling or deployment, maturity of DevOps and observability, and how well you understand the domain boundaries. Default for TiffinBox (10 engineers, one city): a modular monolith with clear modules (subscriptions, scheduling, kitchens, dispatch, payments), extracting a service only when a module has a distinct scaling or ownership need (dispatch's real-time rider tracking is a candidate).
7. Synchronous vs asynchronous
| Synchronous (request/response) | Asynchronous (queues, events) |
|---|---|
| Simple to reason about; immediate result and error | Decouples producers and consumers; absorbs spikes; retries; fan-out |
| Caller waits; failures cascade; availability multiplies (A × B × C) | Eventual results; harder debugging; ordering, duplicates, monitoring of lag |
Decide by: does the user need the result now (skip confirmation: yes, synchronous with a fast database write) or can work happen after (notifying the kitchen tablet, updating analytics, sending a WhatsApp confirmation: asynchronous via events)? A common shape: synchronous for the user's decision, asynchronous for consequences, with the transactional outbox pattern to publish events reliably (Volume 5).
Queues level load: the 06:45–07:00 skip rush can be accepted quickly and processed at the kitchen-sync rate. Little's law (L = λW) relates queue length L, arrival rate λ and wait time W:
def queue_wait_minutes(arrival_per_min, service_per_min, burst_minutes):
"""Backlog built during a burst and how long the last item waits (simple fluid approximation)."""
backlog = max(0, (arrival_per_min - service_per_min) * burst_minutes)
return backlog, round(backlog / service_per_min, 1)
queue_wait_minutes(arrival_per_min=600, service_per_min=250, burst_minutes=15) # 5,250 queued, last waits 21 min
# Kitchens must see skips within 15 minutes (chapter 185's NFR) → raise consumer throughput to ≥ 350/min or batch updates
Availability arithmetic for synchronous chains: three services each at 99.9% in series give ≈ 99.7% (0.999³), about 2 hours of extra monthly downtime: one reason to make non-essential dependencies asynchronous or optional.
8. SQL vs NoSQL
Choose by access patterns, consistency needs and scale, not fashion (Volume 3):
| Relational (PostgreSQL, MySQL) | Key-value / document / wide-column (DynamoDB, MongoDB, Cassandra) |
|---|---|
| Flexible queries, joins, constraints, transactions; schema enforces integrity | Predictable performance at very large scale for known access patterns; flexible documents; easy horizontal scaling (some) |
| Scaling writes beyond one primary needs work (partitioning, distributed SQL) | Queries must be designed up front; joins and ad-hoc analytics are hard; transactions are limited or costlier |
TiffinBox: subscriptions, deliveries, credits and payments are relational, transactional and modest in scale → PostgreSQL. Rider GPS pings (high write rate, time-ordered, short retention) → a time-series store or a stream with TTL. Menu content → Postgres JSONB is enough. "NoSQL vs SQL" is often "which data, which store": polyglot persistence with a small number of well-understood systems.
9. Self-hosted model vs API
For AI features (Volume 14):
| API (hosted frontier or open models) | Self-hosted (open-weight models on your GPUs) |
|---|---|
| Best quality, no infrastructure, pay per token, fast to start | Control (data residency, customisation, fine-tuning), predictable cost at high steady volume, latency control |
| Data leaves your boundary (under contract); rate limits; vendor changes models | GPU capacity, MLOps, serving engineers; utilisation risk; you own safety layers |
Break-even depends on volume, utilisation and the quality you need:
def api_cost_per_month(requests_per_day, in_tokens, out_tokens, in_price_m=0.5, out_price_m=1.5):
return requests_per_day * 30 * (in_tokens * in_price_m + out_tokens * out_price_m) / 1e6
def self_hosted_cost_per_month(gpus, gpu_hour=2.5, utilisation_overhead=1.0, engineer_fraction=0.5, engineer_month=6000):
return gpus * gpu_hour * 24 * 30 * utilisation_overhead + engineer_fraction * engineer_month # USD
for rpd in (20_000, 200_000, 2_000_000):
api = api_cost_per_month(rpd, 1500, 300)
gpus = max(1, int(np.ceil(rpd / 400_000))) # assume one GPU replica serves ~400k such requests/day
print(rpd, round(api), round(self_hosted_cost_per_month(gpus)))
# 20k/day: API $720 vs self-hosted $4,800 · 200k/day: $7,200 vs $4,800 · 2M/day: $72,000 vs $12,000
# small volumes: API is far cheaper; at hundreds of thousands of requests a day self-hosting a small model can win —
# if a small open model meets the quality bar on your evals (chapter 175)
Middle paths: hosted open-model providers, provider-managed dedicated capacity, a gateway that routes easy traffic to a cheap or self-hosted model and hard traffic to an API (chapter 158).
10. Local state vs distributed state
| Local (in-process memory, local disk, sticky sessions) | Distributed (shared database, Redis, distributed cache) |
|---|---|
| Fastest; simplest | Survives instance loss; shared across replicas; enables stateless scaling |
| Lost on restart/deploy; inconsistent across replicas; complicates scaling and failover | Network latency; another system to operate; consistency and invalidation questions |
Guidance:
- Keep application servers stateless; put durable state in databases and shared ephemeral state (sessions, rate-limit counters) in Redis or similar.
- Local caches are fine for read-mostly data with acceptable staleness (menu, configuration) with short TTLs or invalidation events; they're dangerous for anything that must be consistent (credits).
- Client-side state (mobile app) is local state too: design offline queues and conflict handling explicitly.
- For workflows and agents, checkpointed state in durable storage (Volume 14, chapter 171) beats state held in a process.
Communicating trade-offs
Engineers often lose arguments they should win because they explain mechanisms instead of consequences. To product managers and executives:
- Translate into outcomes, risk, time and money: "Option A ships in 3 weeks but every new city needs a code change (≈ 1 week each); Option B takes 5 weeks and new cities become configuration."
- Offer options with recommendations, not a single answer or an open question.
- Make uncertainty explicit ("we're 70% confident in the 3-week estimate") and say what would reduce it (a 2-day spike).
- Distinguish reversible from irreversible choices; propose how to make irreversible ones reversible.
- Write it down (an ADR or a one-page decision memo) and set a review trigger.
Lab: three trade-offs, measured
Setup. Python 3.13 with psycopg 3.3 and redis-py 8.1, PostgreSQL 16 (fsync on, fdatasync, ext4 on the lab VM's virtual disk) and Redis on the lab machine. The email provider is simulated (300 ms per call, 5% of calls take 3 s, 2% fail); the database and queue are real.
Experiment 1: synchronous vs asynchronous side effects
200 "skip" requests, each needing a confirmation email:
| Design | Request p50 | Request p99 | Requests that failed |
|---|---|---|---|
| call the provider inside the request | 300.1 ms | 3,000.2 ms | 3 / 200 |
| enqueue a job in Redis and return | 0.1 ms | 0.4 ms | 0 / 200 |
A single worker then drained the queue with up to 3 attempts per email: 200 sent, 0 lost, and the last email went out 110 s after the burst.
The asynchronous design moved the cost rather than removing it: the user's request became fast and independent of the provider, while the team took on a worker, a retry policy, idempotency (so a retried email isn't sent twice), monitoring of queue depth and failures, and a delay users may notice. Where the side effect must happen before you confirm (charging a card), synchronous is right; where it can follow (a receipt email), asynchronous usually is. Use a transactional outbox if the job must be enqueued if and only if the database change commits.
Experiment 2: durability vs commit latency
2,000 single-row inserts, one client, each its own transaction:
synchronous_commit |
p50 | p99 | Commits per second |
|---|---|---|---|
| on (wait for the WAL to be flushed to disk) | 0.191 ms | 0.333 ms | 5,005 |
| off (acknowledge before flushing) | 0.061 ms | 0.109 ms | 15,402 |
With off, a crash can lose commits acknowledged in roughly the last 3 × wal_writer_delay (200 ms here), but never corrupts the database. This VM's disk flushes in about a tenth of a millisecond; on network-attached cloud disks a flush often takes 1–10 ms, and the gap grows accordingly. The setting can be chosen per transaction, so one database can treat analytics events and payments differently.
Experiment 3: normalised tables vs JSONB documents
200,000 orders with 1–3 dishes each, stored both as orders + order_items tables (B-tree indexes) and as one JSONB document per order (GIN index with jsonb_path_ops):
| Operation | Normalised | JSONB |
|---|---|---|
| storage | 45.5 MB | 51.2 MB |
| fetch one order by ID | 0.07 ms | 0.04 ms |
| count orders containing "pulihora" (50,115) | 5.4 ms | 25.2 ms |
| most popular dish across all orders | 24.6 ms | 112.7 ms |
| rename a dish everywhere | 182 ms | 553 ms |
Documents won where the access pattern is "whole aggregate by key", and lost (by 3–5×) on queries and updates that cut across documents. Both answered identically; the trade-off is speed and simplicity of which operations, so decide from your read and write patterns. Many systems mix them: relational columns for what you query and join, JSONB for flexible attributes you mostly read whole.
Try it yourself
- Add a transactional outbox to Experiment 1 and show that a crash between the database write and the enqueue no longer loses or duplicates emails.
- Rerun Experiment 2 with 8 concurrent clients; does group commit narrow the gap?
- Add a B-tree expression index for a frequently queried JSONB field and remeasure.
- Write an ADR for one of these decisions in your own system, including what would make you revisit it.
Revision sheet: technical trade-offs
Key ideas
- Name the qualities in tension, the context (scale, team, deadlines, risk, regulation) and the reversibility of the decision.
- Classic pairs: simple vs flexible; fast to build vs maintainable; strong consistency vs availability/latency; cost vs performance; build vs buy; monolith vs microservices; sync vs async; SQL vs NoSQL; self-hosted model vs API; local vs distributed state.
- Measure the decisive trade-off with a spike, benchmark or prototype when it's cheap to do so.
- ADRs: context, decision, consequences, status, alternatives; revisit triggers.
- Communicate trade-offs in business terms: cost, risk, time, user impact.
- Prefer reversible decisions and keep options open where uncertainty is high (YAGNI where it isn't).
Numbers to remember
- Lab: sync email p99 3,000 ms vs async 0.4 ms; one worker cleared 200 emails in 110 s.
- Lab:
synchronous_commit=off3× faster commits; loss window ≈ 3 ×wal_writer_delay. - Lab: JSONB 1.75× faster single-document fetch, 3–5× slower cross-document queries and updates.
Pitfalls
- Deciding by fashion or familiarity instead of forces.
- Hiding costs ("async is free").
- Irreversible decisions made quickly; reversible ones made slowly.
- No record of why, so decisions are relitigated or never revisited.
- Benchmarks that don't match real access patterns.
Glossary
- ADR: architecture decision record.
- Transactional outbox: writing an event in the same transaction as the data change, published later.
- Group commit: flushing several transactions' WAL in one disk sync.
- Two-way door: a decision that's cheap to reverse.
- YAGNI: "you aren't gonna need it".