The interviewer asks you to “build DocuSign.” You picture an upload box, a signature pad, and a PDF with a squiggle burned into the bottom. Then they add one sentence: “the signing is multi-party and strictly ordered - the CFO countersigns only after legal and the CEO have both signed - and six months later in court, you must prove no signature was forged, backdated, or reordered, even if someone with database access tried to rewrite history.” Now it is not a form-filling app. It is a workflow engine plus a tamper-evident ledger, and the hard part is making the audit trail trustworthy when you cannot fully trust your own storage.
The core idea the whole design turns on: a signature is not a pixel on a PDF - it is a cryptographic event, chained to the one before it with a hash, and anchored to a trusted third party’s timestamp so that nobody, including the platform operator, can later alter the order or the contents without the break being provable. This post builds that end to end, with the hash chain and the timestamping-authority (TSA) integration front and center.
Functional Requirements (FR)
In scope:
- Document upload and envelope creation. A sender uploads a document (PDF), defines an envelope: the ordered list of signers, what each must do (sign, initial, provide a date), and the signing routing (sequential, parallel, or mixed).
- Sequential multi-party signing with gating. Each signer can only act when it is their turn. Signer N’s signing action is accepted only after every signer with a lower order index has a committed, valid signature. The CFO literally cannot sign before legal and the CEO.
- Signature capture and binding. When a signer signs, we bind their identity, their intent, the exact document bytes they saw, and a trusted timestamp into one cryptographic signature event.
- Tamper-evident audit trail. Every event (viewed, signed, declined, delegated) is appended to a per-envelope hash chain. Any alteration, deletion, or reordering of a past event is detectable by re-verifying the chain. Each signature is anchored to a Timestamp Authority (TSA) so the time cannot be forged even by us.
- Completion and sealing. When the last signer signs, the envelope is sealed: a final document is produced with an embedded certificate of completion, and the whole chain is cryptographically closed.
- Verification. Anyone with the completed document and the audit bundle can independently verify, offline, that the signatures are valid, in order, and were made at the claimed times.
Explicitly out of scope (state it so you own the boundary):
- Identity proofing / KYC. Whether “this email is really the CFO” is someone else’s problem (SSO, government ID checks, SMS OTP). I consume an authenticated identity; I do not design the identity provider.
- The PKI / certificate authority. I assume signers have (or are issued) key pairs and that a CA I trust issues certificates. I design how I use keys and certs, not the CA.
- Document rendering / WYSIWYG editor. How fields get placed visually on the PDF is a front-end concern. I design the binding between “what the signer saw” and “what they signed.”
- Billing, templates, bulk send. Real products have these; they are not the interesting distributed-systems core.
The decision that drives everything: we never trust the time, the order, or the integrity of our own storage on faith. Trust is derived from cryptography - a hash chain for order and integrity, a TSA for time, and signer-held keys for intent - so that the proof survives even a full compromise of our database.
Non-Functional Requirements (NFR)
- Scale: a large B2B platform - ~50M envelopes/year, ~3 signers each on average, so ~150M signature events/year. Peak is bursty (end of quarter, end of month): assume ~2,000 envelope creations/sec and ~6,000 signing actions/sec at peak. Reads (view document, check status) dominate: ~50,000 reads/sec.
- Latency: signing is user-facing and must feel instant - p99 under ~500ms for the local part of a sign action. But a signature is not final until the TSA timestamp returns, and the TSA is a network round trip to an external party (tens to hundreds of ms, occasionally seconds). So we split: the signer’s action commits fast; the trusted-timestamp anchoring completes asynchronously but is still bounded (p99 under ~3s to fully sealed).
- Availability: 99.99% for signing. A signer hitting “sign” during a peak must not get an error. The TSA is a third party and will have blips, so the design must tolerate a temporarily unreachable TSA without blocking signing.
- Consistency: the signing-order gate is strongly consistent - it is a correctness invariant, not a UX nicety. We must never accept signer N’s signature while signer N-1 is unsigned, even under concurrent requests, retries, or races. This needs serialization per envelope.
- Durability: zero loss of signature events and zero silent mutation. A committed signature survives forever and any tampering is detectable. This is stronger than normal durability - it is durability plus tamper-evidence.
- Auditability: the audit trail must be independently verifiable, offline, by a third party (a court, an auditor) using only public primitives (hash functions, signatures, TSA tokens) - not by trusting our API.
The central tension: signing must be fast and highly available, but a signature is only legally meaningful once it is cryptographically anchored to a trusted time and chained into an immutable order - and those anchors depend on an external TSA that is slower and less available than we are. The whole design is about committing the signer’s intent instantly and durably, then completing the trusted anchoring reliably and asynchronously, without ever leaving a window where a signature exists but its order or time could be forged.
Back-of-the-Envelope Estimation (BoE)
Real numbers, because they decide storage strategy and whether the TSA call can be synchronous.
Event volume:
Envelopes/year: 50,000,000
Signers per envelope: ~3 avg
Signature events/year: 150,000,000
Audit events/year: ~5x signatures (view, open, field-fill, sign,
complete) = ~750,000,000 events/year
Per-day signatures: 150M / 365 = ~411,000/day
Peak signing actions: ~6,000/sec (quarter-end bursts)
Peak envelope creates: ~2,000/sec
Peak reads (status/doc): ~50,000/sec (reads dominate ~8:1)
TSA call budget - the key number:
Peak signatures needing a timestamp: ~6,000/sec.
A public RFC 3161 TSA round trip: ~100-800 ms, and TSAs rate-limit.
6,000 individual TSA calls/sec against one external authority is
both expensive and will get us throttled.
=> We CANNOT call the TSA once per signature synchronously at peak.
We must BATCH signatures into a Merkle tree and get ONE timestamp
token per batch, amortizing one TSA call across thousands of events.
This single constraint reshapes the design: trusted timestamping is batched via a Merkle tree, not per-event.
Storage:
Documents:
Avg document: ~500 KB (a few-page PDF), some much larger.
50M envelopes * ~2 versions (original + sealed) * 500 KB
= ~50 TB/year of document bytes -> object storage (S3), not the DB.
Audit chain:
Per event row: event_id, envelope_id, seq, actor, type,
prev_hash(32B), this_hash(32B), payload_hash(32B),
signature(~256B), metadata(~400B) ~= ~1 KB/event
750M events/year * 1 KB = ~750 GB/year of chain rows.
Over 7-year legal retention: ~5 TB. Fits a partitioned SQL store.
Signature tokens + TSA tokens:
Signature blob ~2-4 KB, TSA token ~2-5 KB per batch.
150M sigs * 3 KB = ~450 GB/year. Store alongside the chain or in
object storage keyed by event.
Bandwidth:
Reads: 50,000 reads/sec. Most are status checks (tiny, ~1 KB JSON)
not full document downloads. Full doc downloads maybe ~2,000/sec
* 500 KB = ~1 GB/sec -> served from object storage via CDN, not
through the app tier.
Cache:
Hot set: active (in-flight) envelopes and their current state.
In-flight envelopes at any time ~= 50M/year * (avg 3-day signing
window / 365) = ~410,000 active envelopes. State ~5 KB each
= ~2 GB. Trivially cacheable in Redis. The audit chain itself is
append-only and not latency-critical to read, so it is not cached hot.
The headline: documents go to object storage (50 TB/year), the audit chain is a modest partitioned SQL store (~5 TB over retention), and the only genuinely hard capacity constraint is the TSA - 6,000 timestamps/sec against an external authority is impossible per-event, which forces Merkle batching. That, plus per-envelope serialization for the ordering gate, is where the design spends its effort.
High-Level Design (HLD)
The spine: a sender creates an envelope (document + ordered signers) via the Envelope Service; the document is stored in object storage and a content hash recorded. Each signer is notified in turn. When a signer signs, the Signing Service acquires a per-envelope lock, verifies the ordering gate (all prior signers done), captures the signature, and appends an event to the hash chain in the Audit Store. A Timestamp Service batches recent signature events into a Merkle tree and fetches one RFC 3161 token from an external TSA, writing the token back to anchor the batch. On the final signature, the Sealing Service produces the completed PDF with an embedded certificate. Reads go through a cache and the CDN.
┌──────────────┐
Sender ──create──► │ Envelope │ ──doc bytes──► ┌───────────────┐
│ Service │ │ Object Storage│
│ (workflow) │ ◄──doc hash─── │ (S3) + CDN │
└──────┬───────┘ └───────────────┘
│ defines ordered signers, routing
▼
┌───────────────────┐ notify next signer
│ Notification │ ──email/SMS──► signer
│ Service │
└───────────────────┘
signer opens link, views doc
│
signer clicks "sign" ▼
│ ┌───────────────────────┐
▼ │ Signing Service │
┌──────────────────────────────────────────►│ 1. acquire envelope │
│ │ lock (serialize) │
│ │ 2. ORDER GATE: verify │
│ ┌─────────────────┐ │ all prior signers │
│ │ Lock Service │◄──lease per envelope──│ have valid sigs │
│ │ (Redis / etcd) │ │ 3. compute sig over │
│ └─────────────────┘ │ (doc hash + prev │
│ │ chain hash + meta) │
│ │ 4. APPEND chain event │
│ └───────┬───────────────┘
│ │ append-only
│ ┌───────▼───────────────┐
│ │ Audit Store (SQL) │
│ │ per-envelope hash │
│ │ chain, WORM-backed │
│ └───────┬───────────────┘
│ │ enqueue event id
│ ┌───────▼───────────────┐
│ │ Timestamp Service │
│ │ batch events -> Merkle │
│ │ root -> ONE TSA call │──┐
│ └───────┬───────────────┘ │
│ │ write token back │ RFC 3161
│ ▼ ▼
│ ┌───────────────┐ ┌──────────────┐
│ last signer done ───────────────────────► Sealing Service│ │ External TSA │
│ │ render sealed │ │ (trusted 3rd │
│ │ PDF + cert │ │ party) │
│ └───────────────┘ └──────────────┘
The create path:
- Sender uploads the document. The Envelope Service streams it to object storage and computes
doc_hash = SHA-256(bytes). The hash, not the bytes, is what the chain references. - Sender defines signers with an explicit
order_index(0, 1, 2, …) and routing (sequential here). This is persisted as the envelope’s workflow definition. - The chain is initialized with a genesis event (
seq=0,prev_hash = 0x00..., payload = envelope definition + doc_hash). This roots the chain. - The first signer (order 0) is notified.
The sign path (the correctness-critical one):
- The signer opens their link, authenticates (out of scope), and the exact document bytes are served from object storage via CDN. The client re-hashes what it rendered and the server confirms it matches
doc_hash- the signer signs what they saw. - On “sign,” the Signing Service acquires a lease on
envelope_idso only one signing action per envelope is in flight. This serializes the ordering gate. - Order gate: it reads the chain tail and the envelope definition and verifies that every signer with
order_index < this signer'shas a committed, validSignedevent. If not, reject with409 Conflict(“not your turn”). - It computes the signature event: a digital signature over
H(doc_hash || prev_chain_hash || signer_id || intent || client_nonce), using the signer’s key (or a platform-held key authorized by the signer, depending on the signing model). - It appends the event to the chain:
this_hash = H(prev_hash || payload_hash || signer_sig || seq). This commit is the point of no return - the signature now durably exists and is linked to the prior one. - It enqueues the event id for timestamping and releases the lease. The signer gets a fast success.
- The next signer is notified.
The anchoring path (async, batched):
- The Timestamp Service collects signature events from a short window (e.g. every 1-2 seconds, or every N events), builds a Merkle tree over their
this_hashvalues, and sends the Merkle root to the external TSA. - The TSA returns a signed RFC 3161 timestamp token over that root. The service stores the token plus each event’s Merkle inclusion proof (the sibling hashes on the path to the root).
- Now each signature event is provably “existed at or before time T” where T is attested by a trusted third party - and a single TSA call covered thousands of events.
The seal path:
- When the last signer signs, the Sealing Service renders the final PDF, embeds a certificate of completion (all signers, times, chain head hash, TSA token references), and marks the envelope
completed. The chain is closed with a finalCompletedevent.
The structural insight: the only strongly-serialized, latency-sensitive step is “acquire lock, check order, append to chain” per envelope - and that is cheap because envelopes are independent. Trusted timestamping, the one external and slow dependency, is pulled off the critical path and batched. Correctness of order lives in the per-envelope lock plus the hash chain; correctness of time lives in the TSA tokens; neither depends on trusting our storage.
Component Deep Dive
The hard parts, naive-first then evolved: (1) the sequential ordering gate under concurrency, (2) the tamper-evident hash chain, (3) trusted timestamping via the TSA without per-event calls, (4) surviving a storage compromise so tampering is still provable.
1. The sequential ordering gate: countersign only after all prior parties
The job: signer N’s signature is accepted only after every signer with a lower order index has a committed, valid signature - and this must hold under concurrent requests, retries, duplicate clicks, and failures mid-flight.
Naive approach: check a status column, then write
def sign(envelope_id, signer):
env = db.get(envelope_id)
# is it my turn?
prior = [s for s in env.signers if s.order_index < signer.order_index]
if any(s.status != "signed" for s in prior):
raise Conflict("not your turn")
record_signature(envelope_id, signer) # writes signer.status = signed
Where it breaks:
- Read-check-write race. Two signers (or two retries of one signer) call
signat nearly the same time. Both read the state, both see their preconditions pass, both write. With a parallel-routing bug or an off-by-one in order, you can accept two signatures that each assumed the other had not happened. The check and the write are not atomic. - The gate is advisory, not enforced.
statusis a mutable column. A bug, a replay, or a malicious API call can flip a signer tosignedout of order, and nothing structurally prevents the next signer from proceeding. The “order” is a convention, not an invariant. - Duplicate signatures. A signer double-clicks or a retry fires; without idempotency the same signer gets two signature events, and now “who signed when” is ambiguous - fatal for an audit trail.
- Partial failure. You write
status=signedbut crash before appending the audit event (or vice versa). Now the status and the chain disagree, and the gate is reading a lie.
The status-column approach treats ordering as data to be checked rather than as a serialized, append-only fact. It cannot survive concurrency or a hostile caller.
Evolved approach: per-envelope serialization + the chain itself is the gate
Two changes make the gate correct.
Serialize all signing actions for one envelope. Envelopes are independent, so we need a lock per envelope, not a global one - this scales perfectly (50M independent locks, almost never contended, since one envelope rarely has two people signing the same millisecond, and when it does we want them serialized anyway).
def sign(envelope_id, signer, idempotency_key):
with envelope_lock(envelope_id, lease_ms=5000): # Redis/etcd lease
tail = chain.read_tail(envelope_id) # latest committed event
# idempotency: did this exact action already land?
if chain.has_event(envelope_id, idempotency_key):
return existing_result(envelope_id, idempotency_key)
# ORDER GATE derived from the chain, not a mutable status column:
signed_indices = chain.signed_order_indices(envelope_id)
required = set(range(signer.order_index)) # all strictly before me
if not required.issubset(signed_indices):
raise Conflict("prior signers not complete")
event = build_signature_event(
envelope_id, signer, prev_hash=tail.this_hash,
idempotency_key=idempotency_key)
chain.append(event) # atomic, append-only, see part 2
enqueue_for_timestamp(event.id)
return success(event)
- The lock makes check-and-append atomic. Only one signing action per envelope runs at a time, so “verify prior signers, then append” cannot interleave. The lease has a TTL so a crashed holder does not wedge the envelope forever; on expiry another request can proceed and the append is still safe because it reads the current tail.
- The gate is derived from the chain, not from mutable status.
signed_order_indicesis computed by reading the append-only signature events. There is no column to flip out of band - to make signer N eligible you must have actually appended validSignedevents for all prior indices. Order is now an emergent property of immutable facts. - Idempotency keys kill duplicates. Each sign action carries a client-generated
idempotency_key; it is part of the event and uniquely constrained, so a retry or double-click finds the existing event and returns it rather than appending a second signature. - One atomic commit. The signature event is the status change - there is no separate status write to get out of sync. The chain is the single source of truth for “who has signed.”
For parallel or mixed routing (e.g. “any 2 of these 3, then the CFO”), the gate generalizes: the workflow definition specifies a predicate over completed events (a dependency DAG), and the gate evaluates that predicate against the chain. Sequential is just the special case “all lower indices done.” The lock and the chain-as-truth stay identical.
Why per-envelope locking and not optimistic concurrency? You could use a version/compare-and-set on the chain tail (append only if prev_hash still equals what you read) and retry on conflict. That also works and avoids a lock service - it is the better choice if lock-service ops are a concern. The trade-off: optimistic CAS wastes work under contention (rare here, since one envelope is seldom hot) but removes a dependency; pessimistic leasing is simpler to reason about and bounds latency. Given envelopes are almost never concurrently signed, I default to a short lease, with an optimistic prev_hash CAS as the backstop so even a lease expiry or split-brain cannot produce two conflicting appends.
2. The tamper-evident hash chain
The job: make every event (especially signatures) append-only and ordered such that any deletion, mutation, or reordering of past events is detectable by recomputing hashes - independent of whether you trust the storage.
Naive approach: an audit_log table with a timestamp column
INSERT INTO audit_log (envelope_id, actor, event_type, created_at)
VALUES (:env, :actor, 'Signed', now());
Where it breaks:
- Rows are mutable. Anyone with DB access (a rogue admin, an attacker who got credentials, a buggy migration) can
UPDATEthe timestamp,DELETEa row, orINSERTa backdated one. Nothing about the row proves it was not altered. The audit “trail” is only as trustworthy as your weakest DB credential. created_atis self-asserted. The time is whatever our server’s clock said and whatever got written - trivially forgeable. A backdated contract is oneUPDATEaway, with no evidence left behind.- No ordering proof. Rows have ids and timestamps, but nothing links event N to event N-1. Delete the middle of the log and the remaining rows look perfectly consistent. There is no structural way to notice a hole.
A plain log answers “what do we claim happened.” An audit trail must answer “what provably happened, even if our own records were attacked.” The naive table cannot.
Evolved approach: a per-envelope hash chain (blockchain-of-one)
Each event stores the hash of the previous event, so every event’s hash transitively depends on the entire history before it. Change anything and every subsequent hash changes - the break is visible.
event[0] (genesis):
payload = { envelope_def, doc_hash }
prev_hash = 0x0000...0000
this_hash = H( prev_hash || seq=0 || payload_hash )
event[n] (e.g. a signature):
payload = { signer_id, intent, doc_hash, client_nonce, metadata }
payload_hash = H(payload)
signer_sig = Sign_signerKey( H(doc_hash || prev_hash || signer_id || intent) )
prev_hash = event[n-1].this_hash
this_hash = H( prev_hash || seq=n || payload_hash || signer_sig )
- Integrity. To tamper with
event[k], you must recomputethis_hashforkand every event after it (because each embeds the prior’s hash). The chain head hash is a single value that commits to the entire history. If you publish/anchor the head hash somewhere you cannot later rewrite (the TSA, part 3), silent tampering becomes impossible: the stored chain will no longer hash to the anchored head. - Ordering. The
prev_hashlinks enforce a total order per envelope. You cannot delete a middle event without breaking the next event’sprev_hash, and you cannot reorder two events without their hashes failing to chain. Reordering or deletion is detected by a linear re-verification pass. - Intent binding.
signer_sigis a real digital signature by the signer over(doc_hash, prev_hash, signer_id, intent). It binds who signed what document at what point in the chain. Becauseprev_hashis inside the signed payload, a signature is cryptographically pinned to its position in the sequence - you cannot lift signer 2’s signature and replay it as if it came first, because its signed content includes the hash of everything that was supposed to precede it. - Append-only enforcement in storage. Back the chain with append-only / WORM semantics: a dedicated table where the app only ever
INSERTs, withUPDATE/DELETErevoked at the DB-role level, plus periodic export to object storage with Object Lock (immutable, retention-locked). The hash chain makes tampering detectable; WORM storage makes it hard; the two together mean an attacker must both bypass immutability controls and rewrite the anchored head, which the TSA prevents.
Verification is offline and third-party. Given the event list and the anchored head, a verifier (a court-appointed auditor, a counterparty) recomputes each this_hash from prev_hash and payload, checks each signer_sig against the signer’s certificate, confirms the final this_hash equals the TSA-anchored value, and checks the Merkle inclusion proofs against the TSA tokens. No trust in our API required - just public crypto primitives.
Scaling the chain: per-envelope, not global. A single global chain across all envelopes would serialize every signature on the planet onto one append point - a throughput disaster and a global SPOF. Instead each envelope has its own chain. Envelopes are independent, so their chains append in parallel with no coordination. We get tamper-evidence per document without a global bottleneck. The only thing shared globally is the TSA anchoring, which is batched (next).
3. Trusted timestamping via the TSA, without a call per signature
The job: anchor every signature to a time that even we cannot forge - using an external RFC 3161 Timestamp Authority - without making 6,000 external calls/sec or blocking the signer on a slow third party.
Naive approach: call the TSA synchronously for every signature
def append_signature(event):
token = tsa.timestamp(event.this_hash) # external RFC 3161 call
event.tsa_token = token
chain.append(event) # only now commit
Where it breaks:
- Throughput and cost. 6,000 TSA calls/sec at peak against an external authority: TSAs rate-limit, charge per request, and add 100-800ms latency each. You will be throttled, it will be expensive, and the signer is now blocked on a slow external party for every signature.
- Availability coupling. If the TSA is down or slow (it is a third party - it will be, sometimes), signing stops entirely. You have coupled your 99.99% signing availability to someone else’s SLA. Unacceptable - a signer hitting “sign” during a TSA blip must not fail.
- No batching means no amortization. Each signature pays the full TSA round-trip tax. There is no reason every event needs its own token when a single token can cover a whole batch via a Merkle root.
Synchronous per-event timestamping puts a slow, rate-limited, third-party dependency directly on the hottest user path. It fails on throughput, cost, and availability at once.
Evolved approach: Merkle-batched anchoring, off the critical path
Commit the signature locally first, then anchor a batch with one TSA call.
Step 1 - commit fast, anchor later. The signer’s action appends the event to the chain and returns success immediately. The event is now durable and chained (so its order and integrity are already protected relative to its envelope). It carries a status anchor_pending.
Step 2 - batch into a Merkle tree. A Timestamp Service collects all events across all envelopes from a short window (e.g. 1 second, or 4,096 events, whichever first) and builds a Merkle tree over their this_hash values:
ROOT = H(H01 || H23)
/ \
H01=H(h0||h1) H23=H(h2||h3)
/ \ / \
h0= h1= h2= h3=
evtA.hash evtB.hash evtC.hash evtD.hash
Step 3 - one TSA call for the root. Send only the Merkle ROOT to the TSA. The TSA returns a signed RFC 3161 token attesting “this root existed at time T.” One external call just anchored thousands of signatures.
Step 4 - store inclusion proofs. For each event, store its Merkle inclusion proof - the sibling hashes along its path to the root (for event A: [h1, H23]). Now anyone can prove event A was part of the tree the TSA timestamped: hash A, combine with the siblings up the path, and check you reach the signed root. Mark the events anchored.
- One call amortized over the whole batch. 6,000 signatures/sec at a 1-second batch = one TSA call per second carrying ~6,000 leaves. Cost and rate-limit pressure drop by ~3-4 orders of magnitude. The Merkle tree is
O(log n)proof size per event (~a dozen hashes), trivial to store. - TSA is off the critical path and failure-tolerant. Signing never waits on the TSA. If the TSA is down, events sit
anchor_pendingand the batcher retries with backoff; the signatures are already durable and chained, so nothing is lost - they simply get their trusted timestamp a bit later. We can even anchor the same root to a secondary TSA for redundancy so one authority’s outage does not delay anchoring. The bounded p99-to-sealed (~3s) holds in steady state; during a TSA outage, sealing waits for anchoring but signing keeps working. - Trusted time, not our time. The RFC 3161 token is signed by the TSA’s key, which we do not hold. We cannot backdate it. Combined with the hash chain (which fixes order) this gives the court-grade property: every signature is provably in a fixed order and provably existed before an externally-attested time, neither of which the platform can forge.
Subtlety - the anchor_pending window. Between commit and anchoring, an event has chain-order protection but not yet trusted-time protection. This window is seconds and the event is already immutable in the chain, so an attacker cannot retroactively insert a backdated event into a past, already-anchored position - that would break the already-anchored head. The worst case is a few seconds of events whose trusted time is slightly coarse (bounded by “before the next anchor”), which is acceptable and standard. For regulated flows that need per-signature trusted time, you can additionally request a cheaper local timestamp signed by the platform at commit (weaker, but immediate) and upgrade it with the TSA anchor - belt and suspenders.
4. Surviving a storage compromise: tampering stays provable
The job: the requirement explicitly says forgery or reordering must be detectable even if the platform storage is compromised. So we must not assume our DB is trustworthy.
Naive approach: trust the database, add access controls
Lock down DB access, audit admin actions, encrypt at rest. Where it breaks: every one of these is a control we operate, so an attacker who gets our credentials (or a rogue insider, or a compromised backup) defeats all of them. Access control reduces the chance of compromise; it provides zero evidence after a compromise. The requirement is about evidence, not prevention. If the only thing standing between a forged contract and a court is “we promise our DB was not tampered with,” we have failed.
Evolved approach: externalize the root of trust
The chain and the TSA tokens are built precisely so that the proof does not live inside our trust boundary:
- The head hash is anchored outside our control. Each envelope’s chain head (and the global Merkle roots) are timestamped by the external TSA. An attacker who rewrites our DB cannot rewrite the TSA’s signed tokens - they are signed by a key we do not have. So any rewrite makes the stored chain no longer hash to the TSA-anchored root: the tampering is detectable by anyone, using the TSA’s public certificate.
- Signatures are signer-held, not platform-held (where possible). When signers sign with their own keys, even full control of our storage does not let an attacker forge a new valid signature - they would need the signer’s private key. They can at most delete events, which breaks the chain and is caught. (For platform-managed keys, the keys live in an HSM/KMS with per-signature authorization and their own audit log, so the platform operator alone cannot mint a signature either.)
- WORM + Object Lock + offsite anchoring. The chain is exported append-only to object storage with immutability retention locks, and the periodic Merkle roots are additionally published to an independent append-only transparency log (and optionally a public chain). An attacker must now compromise our DB and our object store’s retention lock and forge the TSA’s key and rewrite the transparency log - which collapses to “forge the TSA’s private key,” the exact thing a trusted third party exists to make infeasible.
- Verification assumes we are hostile. The verifier never calls our API to “confirm” anything. They take the document, the event list, the signer certificates, and the TSA tokens, and check the math. Our role is reduced to custodian of evidence, not authority over truth. That is the whole point: trust is in the cryptography and the third party, not in us.
The progression across the deep dives: order is enforced by a per-envelope lock and proven by the hash chain; integrity is proven by the chain’s linked hashes; time is proven by the external TSA via batched Merkle anchoring; and all three proofs are externalized so they survive a compromise of the very storage that holds them.
API Design & Data Schema
API
POST /v1/envelopes
body: { document_ref | document_bytes, signers:[{email, name,
order_index, required_actions}], routing:"sequential",
message }
-> 201 { envelope_id, status:"created", doc_hash, chain_head }
GET /v1/envelopes/{id}
-> 200 { envelope_id, status, signers:[{..,status, signed_at}],
current_turn_order_index, chain_head }
GET /v1/envelopes/{id}/document # redirect to CDN signed URL
-> 302 Location: https://cdn/.../doc?sig=... (exact bytes, hash-verified)
POST /v1/envelopes/{id}/sign
headers: Idempotency-Key: <client uuid>
body: { signer_token, signed_doc_hash, intent:"I agree",
signature_material } # signer's sig, or auth to platform key
-> 200 { event_id, seq, this_hash, status:"signed",
anchor_status:"pending" }
-> 409 { error:"not_your_turn", current_turn_order_index }
-> 409 { error:"doc_hash_mismatch" } # signer did not see current bytes
POST /v1/envelopes/{id}/decline
body: { signer_token, reason } -> 200 appends a Declined event, halts flow
GET /v1/envelopes/{id}/audit # the full chain + proofs
-> 200 { events:[{seq, type, actor, prev_hash, this_hash,
payload_hash, signer_sig, merkle_proof, tsa_token_ref,
occurred_at}], chain_head, tsa_tokens:[...] }
GET /v1/envelopes/{id}/verify # server-side convenience check
-> 200 { chain_valid:true, all_sigs_valid:true, order_valid:true,
anchored:true, head_matches_tsa:true }
# NOTE: offline verification is the authoritative one; this endpoint
# is a convenience, not the source of trust.
GET /v1/envelopes/{id}/completed-document # sealed PDF + embedded cert
-> 302 Location: https://cdn/.../sealed.pdf
The two gates are visible in the API: 409 not_your_turn enforces ordering, and 409 doc_hash_mismatch enforces that the signer signed the exact bytes served (the client sends back the hash of what it rendered; the server rejects if it does not match the stored doc_hash).
Data stores
1. Envelope / workflow state - SQL (PostgreSQL). Relational, modest volume, needs transactions for the gate and strong consistency on status. Sharded by envelope_id.
Table: envelopes
envelope_id UUID PRIMARY KEY
sender_id UUID NOT NULL
doc_object_key STRING NOT NULL -- pointer to object storage
doc_hash BYTEA(32) NOT NULL -- SHA-256 of the document
routing STRING NOT NULL -- 'sequential'|'parallel'|'dag'
status STRING NOT NULL -- created|in_progress|completed|declined|voided
chain_head BYTEA(32) NOT NULL -- current head hash (denormalized)
created_at TIMESTAMP NOT NULL
Index: (sender_id, status), (status, created_at)
Table: signers
envelope_id UUID NOT NULL
signer_id UUID NOT NULL
order_index INT NOT NULL -- gate order
email STRING NOT NULL
required_actions JSONB
status STRING NOT NULL -- pending|notified|signed|declined
PRIMARY KEY (envelope_id, signer_id)
Index: (envelope_id, order_index)
2. Audit chain - append-only SQL table, WORM-backed, partitioned. The heart of the system. INSERT-only; UPDATE/DELETE revoked at the role level. Partitioned by time for cheap retention management; exported to Object-Locked storage.
Table: chain_events -- append-only, per-envelope chain
envelope_id UUID NOT NULL
seq BIGINT NOT NULL -- 0 = genesis, strictly increasing
event_type STRING NOT NULL -- Genesis|Viewed|Signed|Declined|Completed
actor_id UUID
payload JSONB NOT NULL -- event-specific body
payload_hash BYTEA(32) NOT NULL
prev_hash BYTEA(32) NOT NULL -- links to seq-1
this_hash BYTEA(32) NOT NULL -- H(prev||seq||payload_hash||sig)
signer_sig BYTEA -- signer's digital signature (Signed events)
idempotency_key STRING UNIQUE -- dedup sign actions
merkle_proof JSONB -- sibling hashes to the anchored root
tsa_batch_id UUID -- which TSA batch anchored this
occurred_at TIMESTAMP NOT NULL -- platform-asserted (weak)
PRIMARY KEY (envelope_id, seq)
UNIQUE (this_hash)
Index: (tsa_batch_id), (envelope_id, event_type)
PARTITION BY RANGE (occurred_at) -- monthly; DROP after retention
Table: tsa_batches -- one row per TSA anchoring call
tsa_batch_id UUID PRIMARY KEY
merkle_root BYTEA(32) NOT NULL
tsa_token BYTEA NOT NULL -- RFC 3161 signed token
tsa_authority STRING NOT NULL -- which TSA (for multi-TSA)
anchored_at TIMESTAMP NOT NULL -- TSA-attested time (trusted)
leaf_count INT
PRIMARY KEY (envelope_id, seq)enforces one event per sequence number per envelope - the structural ordering guarantee at the storage layer.UNIQUE (this_hash)catches any accidental or malicious duplicate insert.idempotency_key UNIQUEmakes retried sign actions no-ops.occurred_atis explicitly the weak platform time;tsa_batches.anchored_atis the trusted time. The schema keeps them distinct so verification uses the right one.
3. Documents - object storage (S3) + CDN, with Object Lock. Immutable blobs, huge (50 TB/year), served via CDN. Keyed by doc_object_key. Original and sealed versions both immutable. Object Lock (compliance mode) for the sealed version and the chain export so retention cannot be bypassed even by an admin.
4. Lock service - Redis / etcd. Per-envelope leases for the signing gate. Ephemeral; losing it only forces a re-acquire, not data loss (the prev_hash CAS is the real safety backstop).
5. In-flight cache - Redis. Active envelope state (~2 GB) for fast status reads and gate checks, invalidated on each append.
Why SQL for the core and object storage for blobs: the ordering gate and the chain need transactional, strongly-consistent appends with uniqueness constraints ((envelope_id, seq), this_hash, idempotency_key) - exactly what a relational engine enforces natively, and the volume (~5 TB over 7 years) fits a partitioned SQL store comfortably. Documents are large, immutable, read-heavy blobs - a terrible fit for a DB and a perfect fit for object storage + CDN. NoSQL would not help the chain (we need the constraints and transactions) and would be overkill for the modest row count.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix.
1. TSA throughput and availability (breaks first). 6,000 synchronous external timestamp calls/sec is impossible - throttled, expensive, and couples our availability to a third party. Fix: Merkle-batched anchoring - one TSA call per short window covers thousands of signatures via a single root; store per-event inclusion proofs. Keep timestamping off the critical path (commit first, anchor async) so a TSA blip never blocks signing. Anchor to a secondary TSA for redundancy.
2. Per-envelope serialization becoming global serialization. If the ordering gate used one global lock or one global chain, every signature on the platform would serialize - a hard throughput wall and a global SPOF.
Fix: lock and chain per envelope_id. Envelopes are independent, so their gates and chains run fully in parallel. Shard the envelope and chain stores by envelope_id. The only global coordination left is TSA batching, which is batched anyway.
3. Hot envelope / signing contention. A rare envelope with many signers all prompted at once could see concurrent sign attempts.
Fix: the per-envelope lease serializes them, and the prev_hash CAS rejects any append that raced past the current head - the loser retries, re-reads the tail, re-checks the gate, and either proceeds (now its turn) or gets 409. Contention is naturally low because the gate means usually only one signer is eligible at a time anyway.
4. Chain-store write and growth. 750M events/year of append-only rows, with uniqueness constraints and a hot write path at peak.
Fix: shard by envelope_id, partition by time (monthly) so old partitions are dropped whole after the 7-year retention, and keep the table INSERT-only (no in-place updates, so no dead-tuple bloat). The partial-but-constrained indexes ((envelope_id, seq), this_hash) stay efficient because each shard holds a slice.
5. Read load - status and document fetches (50,000/sec). Reads dominate 8:1 and would swamp the app/DB tier. Fix: serve document bytes entirely from object storage via CDN (signed URLs), never through the app tier; cache active-envelope status in Redis (~2 GB hot set) invalidated on append; the audit chain is read rarely (verification time) and goes straight to the partitioned store or object storage. Read replicas for the envelope DB absorb status queries that miss cache.
6. Single points of failure. The lock service, the TSA, the sealing service.
Fix: lock service runs as a replicated cluster (Redis Sentinel / etcd Raft) and, crucially, is not the correctness backstop - the prev_hash CAS in the append is, so a lock-service outage degrades to optimistic concurrency, not incorrectness. The TSA is dual-sourced and off the hot path. Sealing is an idempotent async worker - a crash mid-seal just re-runs from the committed chain, since the sealed PDF is a pure function of the completed chain.
7. Signer private-key availability (platform-managed keys). If keys live in a KMS/HSM, that becomes a dependency on the sign path. Fix: KMS/HSM is a highly-available managed service; cache short-lived signing authorizations; and prefer signer-held keys where the signing model allows, which removes the platform-key dependency entirely and strengthens the “survives storage compromise” property (we never hold the key that could forge a signature).
8. Verification cost at scale. Verifying a long chain or a legal-discovery batch is O(n) hashing and signature checks.
Fix: verification is offline and infrequent, so cost is fine, but we precompute and store the chain_head and anchor references so a quick check (“does the stored head still match the TSA token?”) is O(1); full re-verification is reserved for disputes. Merkle inclusion proofs are O(log n) per event.
Shard keys / partitioning, stated plainly: envelopes, signers, and the chain all shard by envelope_id - the natural unit of independence, so one document’s entire workflow and chain live on one shard and append without cross-shard coordination. The chain additionally partitions by time (occurred_at, monthly) for retention drop. Documents key by doc_object_key in object storage, fronted by CDN. The TSA batch store is tiny and global (one row per anchoring call). There is deliberately no global chain - that would reintroduce the exact serialization bottleneck sharding is meant to remove; cross-envelope integrity is provided instead by the shared TSA roots and the optional transparency log.
Wrap-Up
The trade-offs that define this design:
- Fast local commit, trusted anchoring deferred. Signing must feel instant and stay available at 99.99%, but a signature is only court-grade once anchored to an external TSA that is slower and flakier than we are. We commit the signature to the hash chain immediately (durable, ordered) and anchor a batch to the TSA asynchronously. The brief
anchor_pendingwindow trades a few seconds of trusted-time coarseness for availability and throughput, and the chain already protects order and integrity during that window. - Order enforced by a lock, proven by the chain. A per-envelope lease (with a
prev_hashCAS backstop) serializes the gate so correctness holds under concurrency; the append-only hash chain makes the resulting order an immutable, verifiable fact rather than a mutable status column. Per-envelope, not global, so it scales to 50M independent chains with no central bottleneck. - Trust externalized, so proofs survive a compromise. The requirement is about evidence after a breach, not prevention of one. We put the root of trust outside our storage - signer-held keys, TSA-signed timestamps, WORM/Object-Lock exports, an independent transparency log - so that an attacker with full database access can at most break the chain (detectable) but cannot forge a valid, in-order, correctly-timed signature without the signer’s key and the TSA’s key, which they do not have.
- SQL for the ledger, object storage for the bytes, batched Merkle for the TSA. Each hard constraint gets the system built for it: constrained transactional appends to Postgres, immutable blobs to S3+CDN, and one amortized external timestamp call per batch instead of per signature.
One-line summary: give every envelope its own append-only cryptographic hash chain, gate each signer behind a per-envelope lock plus a chain-derived order check so a party can countersign only after all prior parties have valid committed signatures, and anchor batches of signature events to an external RFC 3161 timestamp authority via Merkle roots - so the order, integrity, and time of every signature are provable by anyone, offline, even if the platform’s own storage is fully compromised.
Comments