Architecture Documentation and Communication Questions
Making an architecture legible to others: architecture decision records (templates, alternatives and consequences, lifecycle, supersession, tagging and discoverability), diagramming and visualization (C4, sequence, deployment, data-flow and trust-boundary diagrams, notation conventions), and communicating designs to technical and non-technical stakeholders. Covers capturing rationale, documenting what a system does under failure, load and consistency trade-offs, recording observability, SLO and security content, running design reviews, keeping docs and diagrams current, and presenting a system clearly under time pressure. The communication skill that separates a good design from an understood one.
You have a list of service-dependency pairs. Write a function that produces a Graphviz DOT graph from them, and explain why you might generate diagrams from data rather than draw them by hand.
Sample Answer
Approach
Turn the pairs into a set (removing duplicates), sort nodes and edges so the output is identical on every run, and emit one node line and one edge line per item in the DOT language (Graphviz's plain-text graph format: a -> b; means a directed edge). Escape quotes so an odd service name cannot break the file. The same structured data also produces a markdown summary table, so the diagram and the documentation come from one source.
Code (save as archdocs.py)
import json
import sys
def esc(text):
return text.replace("\\", "\\\\").replace('"', '\\"')
def to_dot(pairs, owners=None):
owners = owners or {}
edges = sorted(set(pairs)) # dedupe + stable order
nodes = sorted({n for pair in edges for n in pair} | set(owners))
lines = ["digraph services {", " rankdir=LR;", " node [shape=box];"]
for n in nodes:
label = esc(n) + ("\\n(" + esc(owners[n]) + ")" if n in owners else "")
lines.append(f' "{esc(n)}" [label="{label}"];')
for src, dst in edges:
lines.append(f' "{esc(src)}" -> "{esc(dst)}";')
lines.append("}")
return "\n".join(lines)
def to_markdown(services):
rows = ["| Service | Owner | SLO | Diagram |", "|---|---|---|---|"]
for name in sorted(services):
s = services[name]
rows.append(f"| {name} | {s['owner']} | {s['slo']} | [{s['diagram']}]({s['diagram']}) |")
return "\n".join(rows)
if __name__ == "__main__":
mode, path = sys.argv[1], sys.argv[2]
with open(path) as f:
data = json.load(f)
if mode == "dot":
owners = {n: s["owner"] for n, s in data["services"].items()}
print(to_dot([tuple(e) for e in data["edges"]], owners))
else:
print(to_markdown(data["services"]))
Sample input, saved as services.json, then two runs:
cat > services.json <<'EOF'
{
"edges": [["web", "auth"], ["web", "catalog"], ["catalog", "db"], ["auth", "db"], ["web", "auth"]],
"services": {
"auth": {"owner": "identity-team", "slo": "99.9% login success", "diagram": "docs/auth.svg"},
"catalog": {"owner": "catalog-team", "slo": "p95 < 300 ms", "diagram": "docs/catalog.svg"}
}
}
EOF
python3 archdocs.py dot services.json
python3 archdocs.py table services.json
Output of the first run (the duplicate web -> auth pair appears once):
digraph services {
rankdir=LR;
node [shape=box];
"auth" [label="auth\n(identity-team)"];
"catalog" [label="catalog\n(catalog-team)"];
"db" [label="db"];
"web" [label="web"];
"auth" -> "db";
"catalog" -> "db";
"web" -> "auth";
"web" -> "catalog";
}
Output of the second run:
| Service | Owner | SLO | Diagram |
|---|---|---|---|
| auth | identity-team | 99.9% login success | [docs/auth.svg](docs/auth.svg) |
| catalog | catalog-team | p95 < 300 ms | [docs/catalog.svg](docs/catalog.svg) |
Reading the code line by line
escputs a backslash before\and", so a name likea"bcannot end the quoted string early.edges = sorted(set(pairs)): thesetdrops the duplicate("web", "auth"), andsortedmakes the order the same on every run.nodes = sorted({n for pair in edges for n in pair} | set(owners)): a set comprehension that loops over each pair and then each name in it, so every service is listed once even if it appears in many pairs; the| set(owners)adds services that have an owner but no dependency edges, which would otherwise vanish from the picture (an isolated service is exactly the kind of gap a landscape diagram should show).rankdir=LR;tells Graphviz to lay the graph out left to right (the default is top to bottom);node [shape=box];makes every node a rectangle unless overridden.- The node loop writes one line per service, adding the owner on a second label line (
\nis a line break inside a DOT label) when one is known; the edge loop writes"src" -> "dst";. to_markdownbuilds one table row per service from the same data; SLO means service-level objective, the reliability target the team commits to (for example "p95 < 300 ms", meaning 95 percent of requests finish under 300 milliseconds).
Pipe the DOT output into dot -Tsvg (from the Graphviz tools) to get an image, or paste it into any online Graphviz viewer.
Why generate diagrams from data instead of drawing them
- Single source of truth: the dependency list already lives in a service catalog or config. A diagram built from it cannot disagree with it.
- Stays current: regenerate on every merge in continuous integration (CI, the automated build), so the picture never lags behind the system.
- Reviewable: a change to the dependency list appears as a small text diff in a pull request, which a screenshot of a hand-drawn box cannot offer.
- Consistent: every diagram gets the same shapes and names, which removes the arguments about icons.
- Cost of hand-drawing: nicer layout and emphasis. I would still hand-draw the executive overview and generate the detailed dependency views.
Complexity
Building the set is O(E) for E pairs and sorting is O(E log E) (nodes are at most 2E plus the number V of owned services), so the cost is O((E + V) log (E + V)), with O(E + V) memory for the output.
Edge cases
- Duplicate pairs are removed by the set.
- Names with quotes or backslashes are escaped (
to_dot([('a"b', 'c')])yields the node"a\"b"). - A service with no owner in the data gets no owner line, which is itself a useful documentation gap to flag.
- A service that is in the service data but appears in no pair is still drawn, as an unconnected box, because its name comes from the owners map.
- Cycles are valid in DOT and drawn as-is, which is helpful because circular dependencies are worth seeing.
- Very large graphs (hundreds of nodes) become unreadable: filter to one domain, or one hop from a chosen service, before drawing.
You are documenting a message-bus-based ingestion pipeline. What must the documentation tell producers, consumers and operators, and how would you diagram it so delivery guarantees and failure behaviour are unambiguous?
Sample Answer
Direct answer
A message-bus pipeline document is a contract with three audiences. Producers need to know what to send and what is promised on publish. Consumers need the delivery, ordering and duplicate rules, and what happens to a message that fails. Operators need retention, partition, capacity, alerts and replay steps. The diagram must show partitions, retries and the dead-letter path explicitly, because those are where delivery guarantees are decided.
Vocabulary first
- Broker: the server that receives messages and holds them until consumers read them.
- Topic: a named log of messages on the broker, like one labelled mailbox stream (here
model-updates). - Partition: one slice of a topic's log; messages with the same key always land in the same partition, which is why order is kept per key. The key is hashed to a number and mapped to a partition (for example hash 17 on 6 partitions is 17 mod 6 = partition 5).
- Consumer group: a set of consumers that share a topic, each partition going to exactly one member. With 6 partitions, at most 6 consumers in a group do useful work.
- Offset: a message's position number in its partition. Commit offset (acknowledge) means the consumer tells the broker "I have finished everything up to here", so a restart resumes after it.
- Retry with backoff: try again after a growing wait (for example 1 s, 4 s, 16 s) rather than hammering a failing system.
- Dead-letter topic: a separate topic where messages that keep failing are parked for a human, so they do not block the rest.
- Consumer lag: how many messages a consumer is behind the newest one in its partition.
- Retention: how long the broker keeps messages (here 7 days), which also limits how far back you can replay.
- Local outbox: a table in the producer's own database where the event is saved first, then sent to the broker later, so a broker outage cannot lose it.
What the document must tell each audience
| Audience | Must know |
|---|---|
| Producers | Topic name and owner; the message key and why (ordering scope); schema and version; when a publish counts as done; behaviour when the broker is down; size and rate limits |
| Consumers | Delivery guarantee (at-least-once); ordering scope; the idempotency key; retry policy and dead-letter behaviour; how far back they can replay; consumer group naming; schema deprecation policy |
| Operators | Retention and partition count; consumer lag and dead-letter depth alerts; replay and dead-letter runbooks; capacity and quotas; who is on call |
Delivery semantics in plain terms
- At-least-once: a message is redelivered if the consumer does not acknowledge it, so duplicates are possible. It is the honest default: consumers acknowledge after processing succeeds.
- Exactly-once: across a network you cannot generally guarantee a message is delivered once. Some brokers offer transactional exactly-once inside the broker boundary, but side effects outside it (a database write, an email) still need protection. The practical claim to document is "at-least-once delivery plus an idempotent consumer", meaning processing the same message twice has the same effect as once, achieved by recording processed event ids.
- Ordering: guaranteed only within one partition (a subset of the topic's log). Choosing the key decides what stays ordered.
Diagram: partitioning, consumer groups, retry and dead-letter
flowchart LR
P[Producer] -->|key = model_name| T
subgraph T[Topic model-updates: 6 partitions, retention 7 days]
P0[Partition 0]
P1[Partition 1]
P5[Partition 5]
end
P0 --> C1[Consumer A in group scorer]
P1 --> C2[Consumer B in group scorer]
P5 --> C2
C1 -->|success: commit offset| OK[Acknowledged]
C1 -->|failure: up to 3 retries with backoff| R[Retry topic]
R --> C1
R -->|still failing| D[Dead-letter topic, 14 days]
D --> O[Alert and replay runbook]
Reading the diagram: partitions 2 to 4 are left out for readability. Trace one failing message: it arrives on partition 0, Consumer A fails to process it, so it is sent to the retry topic and comes back to Consumer A after a wait; after 3 failed retries it moves to the dead-letter topic, an alert fires, and an operator follows the replay runbook. On success the consumer commits the offset and the message is done.
Example: model-update publisher and its versioned event contract
A publisher announces each new machine-learning model version. Key by model_name so version 7 is never processed before version 6 for the same model. Consumers ignore any event whose version is not newer than the one they hold, which also makes duplicates harmless. Trace: a consumer holds version 13. Event version 14 arrives, it is newer, so the consumer applies it and now holds 14. The same event is redelivered because the acknowledgement was lost (a duplicate): 14 is not newer than 14, so it is ignored. A late version 13 arriving afterwards is also ignored.
{
"event_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"event_type": "model.updated",
"schema_version": "1.2",
"occurred_at": "2026-09-28T09:15:00Z",
"model_name": "fraud-scorer",
"model_version": 14,
"artifact_uri": "registry://models/fraud-scorer/14"
}
Schema evolution rules
- Adding an optional field is safe: old consumers ignore it.
- Removing, renaming or changing the type of a field is breaking: publish to a new versioned topic (for example
model-updates.v2) and run both for a deprecation window. - Never reuse a field name with a new meaning.
- Every event carries
schema_version; consumers must tolerate unknown fields.
Failure behaviour, stated unambiguously
| Situation | What happens |
|---|---|
| Consumer crashes mid-message | Offset not committed, message redelivered (duplicate possible) |
| Message keeps failing | Three retries with backoff, then dead-letter topic and an alert |
| Broker unavailable to producer | Publish fails and is retried by the producer; document whether the caller is blocked or the event is queued in a local outbox |
| Partition count increased | Key-to-partition mapping changes (the key is hashed then reduced by the partition count: hash 17 goes to partition 5 of 6 but partition 1 of 8), so events for one key can end up in a different partition than earlier ones and ordering can briefly break; do it in a planned window |
Pitfalls: saying "exactly-once" without saying where; a diagram with a single arrow labelled "queue"; forgetting that the dead-letter topic needs an owner and an alert, or it becomes a silent graveyard.
How would you show latency budgets, throughput, error rates, contracts and owners directly on service diagrams, and what conventions would you standardise so the annotations stay readable?
Sample Answer
Direct answer
I annotate the diagram with a small, fixed set of fields on a fixed place: owner as a badge on each box, contract as a link ID on each arrow, and the numbers (latency budget, throughput, error rate) as a short one-line label per arrow. Anything beyond that goes in a table under the diagram, and the numbers are generated from monitoring and contract files so they carry an "as of" date and do not rot.
The conventions I would standardise
- Node (a service box): name from the service catalog, plus a badge with the owning team, for example
pricing-api | team: pricing. - Edge (an arrow): one line, always in the same order:
contract | p95 budget | rate | error-rate target, for examplepricing-v2 | p95 150 ms | 300 rps | err < 0.1%. (p95 means the 95th percentile: 95 percent of requests are faster than this. rps means requests per second. The last field is the highest acceptable share of failed requests, 0.1 percent here. It is a per-request target, not the SRE "error budget", which is the total failure allowance over a period, derived from a reliability target.) - Colour is reserved for one meaning, health against target (green, amber, red), never for teams.
- A legend on every diagram, and an "as of" date.
- Limit: about 12 boxes and one annotation line per arrow; more goes into a table or a separate diagram.
- Contract means a link to the API specification (for example an OpenAPI document, a machine-readable description of an HTTP API's endpoints and message shapes) and its version, not prose.
Component-diagram tutorial box
pricing-api (owner: pricing team, contract: pricing-v2 OpenAPI spec, p95 budget 150 ms). Someone reading the box knows what it is, whom to page, which interface to read, and how slow it is allowed to be.
Latency budgets on the critical path
The critical path is the longest chain of calls the user waits for. Steps that run in parallel count as the slowest of them. Illustrative checkout with an end-to-end p95 target of 800 ms:
| Step | Budget (ms) |
|---|---|
| Gateway | 50 |
| checkout-service own work | 100 |
| pricing (150) in parallel with inventory (120) | 150 (the larger of the two) |
| payments | 300 |
| Total on the critical path | 600 |
50 + 100 + 150 + 300 = 600 ms, leaving 200 ms (25 percent) of headroom under 800 ms. Adding percentiles is an allocation rule, not exact statistics, and it is conservative only for calls in series. For the parallel pair the larger budget slightly understates the risk: if pricing and inventory were independent and each met its own p95, both would be within budget only about 90 percent of the time (0.95 x 0.95 = 0.9025), and reaching 95 percent for the pair would need each side at about its 97.5th percentile (0.95 ** 0.5 = 0.9747). That is one more reason to keep the 200 ms of headroom. The p95 of a chain is not the sum of each step's p95: a request is rarely unlucky in every step at once, so the true combined p95 is usually lower than the sum, but correlated slowness (for example a busy database slowing several steps together) can break that. So I treat the sum as a budget to allocate and keep headroom instead of budgeting to the last millisecond.
Instrumentation placement
Put a trace span (a timed record of one operation, from distributed tracing) at each service entry and around each outbound client call, on the critical path only. Then the diagram's numbers come from the measured span durations, and the difference between a caller's client span and the callee's server span reveals network or queueing time. For example, if checkout's client span around the call to payments lasts 340 ms but payments' own server span lasts 290 ms, the other 50 ms went to the network, connection setup or waiting in a queue before payments started work, and that 50 ms is invisible if only one side is measured.
Trade-offs and pitfalls
- Hand-typed numbers go stale; generate annotations from the monitoring configuration and contracts, or show them with a date.
- Annotating every arrow makes the diagram unreadable: annotate the critical path and the arrows that have a service-level objective, and leave the rest. (A service-level objective, SLO, is the reliability target a team commits to, such as 99.9 percent of requests succeeding.)
- Throughput and error rate are observed values, while budgets are targets. Label which is which, otherwise readers cannot tell "allowed" from "actual".
Here is a one-line architecture description for an analytics ingestion pipeline: 'Clients -> API -> Load Balancer -> Ingest Service -> Batch Processor -> Data Warehouse'. What is missing or misleading, and how would you redraw and narrate it for a design review?
Sample Answer
Direct answer
The one-liner is misleading because it draws a straight chain of boxes, which reads as "every hop is a synchronous call between single instances". In reality this pipeline has a real-time front half (clients, load balancer, ingest) and a scheduled back half (batch, warehouse), and the interesting design decision, the durable buffer between them, is missing entirely. I would redraw it as labeled layers (a durable queue holds messages until consumed and is built for replay; object storage holds files cheaply for later batch reads; stateless means any instance can serve any request because none keeps user state), show the buffer, label every arrow with protocol and sync/async, and narrate it in about a minute: request path, then storage, then batch path, then failure path.
What is missing or misleading
- Order is wrong or ambiguous. "Clients -> API -> Load Balancer" puts the API before its own load balancer. Usually the load balancer sits in front and spreads traffic across several API/ingest instances.
- API and Ingest Service are two boxes with no stated difference. Is one an authentication gateway and the other a validator? Name the responsibility.
- No buffer between Ingest and Batch Processor. How does data cross? A queue, files in object storage, a stream? This decides durability and replay.
- The batch trigger is unstated. Hourly schedule, or event-driven when files land?
- Arrows carry no meaning. No protocol, no payload format, no sync/async, no volumes.
- Failure paths are absent. Bad records (dead-letter queue, DLQ), retries, duplicates from client retries, and late-arriving events.
- Missing artefacts: trust boundary (a line on the diagram where traffic passes from untrusted, such as the internet, to trusted internal systems), ownership, freshness target (how old warehouse data may be), and data retention. The DLQ (dead-letter queue) is where events that repeatedly fail validation are parked for inspection instead of blocking the rest.
Redrawn version
flowchart LR
C[Clients] -->|HTTPS, JSON events| LB[Load balancer]
LB --> I[Ingest service, N stateless instances]
I -->|async append| Q[(Durable queue)]
Q --> R[(Raw files in object storage, hourly partitions)]
R -->|scheduled hourly| B[Batch processor]
B -->|bulk load| W[(Data warehouse)]
I -.->|invalid events| D[(DLQ)]
Worked example: narration for the review (about 60 seconds)
"Clients send JSON events over HTTPS. The load balancer spreads them across stateless ingest instances, which validate the schema and acknowledge only after the event is appended to a durable queue. Bad events go to a DLQ. The queue is drained into raw files in object storage partitioned by hour, so we can replay. Every hour a batch processor reads a partition, deduplicates on event ID (drops any event whose ID it has already loaded, since clients retry) and bulk-loads the warehouse (inserts a whole partition in one operation rather than row by row). Freshness target is about one hour plus load time. The risk I want feedback on: what happens when the batch job overruns its hour."
Variant 1: an event-driven pipeline ("Producer -> Kafka topic -> OrderService -> BillingService"). Kafka is a distributed log; producers append events to a named topic and consumers read at their own pace. Three documentation improvements: (1) name the topic, its key (events with the same key go to the same partition, and order is guaranteed only within a partition) and the event schema; for example topic orders.placed, key orderId, so all events for order 1042 stay in order; (2) state delivery semantics (at-least-once: a message may be delivered more than once) and that OrderService and BillingService consumers are idempotent (processing the same event twice has the same effect as once); (3) show the failure path: retry topic and DLQ, and who owns replay (re-reading old events to rebuild or repair downstream data). Interviewers ask about the main pipeline redraw far more often than this variant.
Variant 2: critiquing vague prose. Take the sentence "The system ingests events and processes them reliably at scale." Edits: replace "reliably" and "at scale" with mechanisms and numbers you can defend (durable append before ack; target events per second); name components; and add missing artefacts (diagram legend, sequence of the failure path, ownership, data-retention statement). Rewritten: "Ingest instances validate each event and acknowledge it only after it is appended to a durable queue; a batch job loads the warehouse hourly, so data is at most about 65 minutes old (TBD, owner: data platform)."
Trade-offs and pitfalls
- Do not turn the redraw into a full inventory; a review diagram shows the decisions to debate.
- Never invent volumes in the diagram; mark unknowns as "TBD, owner named".
Which testing and resilience artifacts belong in architecture documentation so teams can validate the system, and how would you document a failover test plan with hypothesis, steps and expected outcomes?
Sample Answer
Direct answer
Architecture documentation should include the artifacts that let a team prove the design behaves as claimed: a test strategy, a list of failure modes with the expected behaviour, capacity and performance targets with load-test results, recovery objectives with backup-restore evidence, and resilience experiment plans. A failover test plan is written as a hypothesis, a controlled set of steps, expected outcomes with pass and fail criteria, and an abort and rollback path.
Artifacts that belong
| Artifact | Purpose |
|---|---|
| Failure-mode table | For each dependency: what if it fails, expected system behaviour, detection |
| Recovery targets | RTO (recovery time objective: how long an outage may last) and RPO (recovery point objective: how much data loss is tolerable), with the last measured result |
| Load and capacity test plan | Expected peak, headroom, and how it was validated |
| Backup restore test | Date, result, restore time |
| Failover and chaos plans | Below |
| Staging-parity notes | How the test environment differs from production, so results are read with the right caution |
Failover test plan (worked example, illustrative)
Terms used below: the primary is the database instance currently taking writes; a replica is a continuously updated copy that can take over; promoting the replica makes it the new primary; replica lag is how far behind the primary the copy is, in seconds of writes; staging is the production-like test environment; synthetic load is fake but realistic traffic generated by a tool; steady state is the normal measurable behaviour (for example 99% of orders succeed).
Title: Primary database failover, orders service
Hypothesis: If the primary database instance is stopped, the replica is promoted
and orders resume within the 5 minute RTO, with no more than
the 1 minute RPO of writes lost.
Environment: Staging, sized as production-lite (see parity notes)
Preconditions: steady synthetic load; dashboards open; on-call informed;
abort criteria agreed.
Steps:
1. Record baseline: order success rate, latency, replica lag.
2. Stop the primary instance.
3. Observe detection time and promotion.
4. Watch application reconnect behaviour and errors.
5. Restore the old primary as a replica.
Expected: Alert fires within 1 minute; promotion completes; success
rate returns to baseline; no duplicate or lost confirmed orders.
Pass/fail: Recovery within RTO and data loss within RPO, else fail.
Abort: Success rate stays under 50% for 10 minutes: roll back per runbook.
Record: Actual times, surprises, follow-up tickets, date of next test.
Judging the result against the targets (worked numbers, illustrative)
- Primary stopped at 10:00:00. Alert fired 10:00:40. Replica promoted 10:02:30. Order success back to baseline 10:03:00. Recovery took 3 minutes, inside the 5 minute RTO: pass on time.
- Replica lag recorded at the moment of the stop was 20 seconds, so at most 20 seconds of writes could be lost, inside the 1 minute RPO: pass on data.
- Had success only recovered at 10:07:00, recovery would be 7 minutes, above the 5 minute RTO, so the test fails even if no data was lost. Both conditions must hold.
Failure-mode table, one example row
| Dependency | Failure | Expected behaviour | Detection |
|---|---|---|---|
| Orders primary database | Instance stops | Replica promoted, orders resume within 5 minutes, at most 1 minute of writes lost | Alert on failed health checks within 1 minute |
Chaos engineering plan. Chaos engineering means deliberately injecting failure in a controlled way to find weaknesses. Document each experiment as: steady-state definition (the normal measurable behaviour), hypothesis, blast radius (the limit on what could be affected), injected fault, abort conditions, and findings. Start in staging, then move to production only with a small blast radius and abort switches.
Staging parity. List what differs from production (instance sizes, data volume, network topology, third-party stubs). A failover that recovers in staging with a tiny dataset says little about recovery time with production data, so state which conclusions transfer and which do not.
Pitfalls: a plan with no expected outcome (cannot fail); tests never rerun after architecture changes; results not stored beside the design.
Unlock Full Question Bank
Get access to all 38 Architecture Documentation and Communication interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.