Formal Verification with TLA+
When to Recommend Formal Verification
Decision Tree
Is the system distributed or concurrent?
|
+-- No --> Complex state machine with high failure cost?
| +-- No --> NOT cost-effective. Use property-based testing.
| +-- Yes --> CONSIDER TLA+
|
+-- Yes --> Consensus, coordination, or distributed transactions?
| +-- Yes --> RECOMMEND TLA+
| +-- No --> Could concurrency bug cause data loss or safety issues?
| +-- Yes --> RECOMMEND TLA+
| +-- No --> OFFER as option
Strong Indicators (Recommend)
| Domain |
Why TLA+ Adds Value |
Evidence |
| Distributed consensus (Paxos, Raft) |
Subtle interleaving bugs in leader election |
Raft TLA+ spec ~400 lines, found implementation bugs |
| Financial distributed transactions |
Atomicity violations cause monetary loss |
AWS DynamoDB replication verified |
| Leader election, distributed locking |
Split-brain, deadlock, stale-lock |
AWS lock manager verified |
| Eventual consistency / CRDTs |
Convergence proofs required |
TLA+ CRDT framework verifies SEC |
| Safety-critical state machines |
Regulatory requirements |
DO-178C, CENELEC recognize formal methods |
| Multi-party coordination (sagas, 2PC) |
Compensation ordering, partial failure |
2PC is canonical TLA+ example |
| Data replication protocols |
Ordering, consistency under failure |
Elasticsearch, MongoDB, Cosmos DB verified |
When NOT to Use
- Simple CRUD (bugs are in implementation, not design)
- Single-process without complex state machines
- Prototypes/MVPs (design will change before verification completes)
- Performance optimization (TLA+ models correctness, not performance)
Cost-Benefit Reference
- Learning curve: 2-3 weeks to useful results (AWS engineers, all levels)
- Typical spec effort: 2-4 weeks part-time for a distributed protocol
- ROI highest when: bug cost is high, system is long-lived, protocol is novel, concurrency testing is impractical
Core Concepts for Architects
What TLA+ Specifies
TLA+ describes what a system should do (allowed behaviors), not how to implement it. Specifications are mathematical objects checked for correctness before any code exists.
Safety vs. Liveness
| Property Type |
Meaning |
Expression |
Example |
| Safety |
Nothing bad happens |
Invariant: predicate true in every reachable state |
"Two processes never hold same lock" |
| Liveness |
Something good eventually happens |
Temporal: <> (eventually), []<> (infinitely often) |
"Every request eventually gets response" |
Safety violations produce counterexample traces (the debugging artifact). Liveness requires fairness conditions.
PlusCal vs. Raw TLA+
PlusCal compiles to TLA+ with programming-like syntax. Start with PlusCal for first 2-3 specs, then learn raw TLA+ for cases PlusCal cannot express.
Key PlusCal constructs: variables (state) | labels (atomic action boundaries) | either/or (nondeterministic choice) | await (blocking) | process \in 1..N (concurrent processes) | fair process (weak fairness)
Labels define concurrency granularity: everything between two labels is one atomic step. Two processes interleave only at label boundaries.
State Explosion Management
State space grows exponentially: (states per node)^(nodes) x (message permutations).
Containment Strategies
| Strategy |
Technique |
Impact |
| Bound parameters |
Start with 2-3 nodes, 2-4 messages |
Most bugs appear at small N |
| Symmetry reduction |
SYMMETRY Permutations(Nodes) |
Up to N! reduction |
| Reduce labels |
Merge labels where fine-grained atomicity unnecessary |
Orders of magnitude |
| State constraints |
CONSTRAINT Len(log[n]) < MaxLogLength |
Prune uninteresting states |
| Abstraction |
Model protocol not implementation (TCP -> message set) |
Dramatic reduction |
| Decomposition |
Multiple focused specs, not one monolith |
Each independently checkable |
| Progressive refinement |
2 nodes -> 3 nodes -> add failures -> add liveness |
Incremental verification |
| Simulation mode |
java -jar tla2tools.jar -simulate -depth 100 |
Trades completeness for speed |
Memory and Time Budgets
| Unique States |
Expected Time |
Memory |
Approach |
| < 10K |
Seconds |
< 1 GB |
Exhaustive, single thread |
| 10K - 1M |
Minutes |
1-4 GB |
Exhaustive, -workers auto |
| 1M - 100M |
Hours |
4-32 GB |
Exhaustive with constraints |
| 100M - 1B |
Days |
32-64 GB |
Large instance or simulation |
| > 1B |
Weeks |
60+ GB |
Simulation, TLAPS, or decompose |
Estimation Before Running
- Count distinct variable values in model
- Multiply domains together for baseline
- Start TLC with smallest parameters, observe state count
- Extrapolate: doubling a parameter typically squares or cubes the space
Key Specification Patterns
Two-Phase Commit (2PC)
- Variables: rmState, tmState, tmPrepared, msgs
- Safety: no RM commits while another aborts (
Consistency)
- State space: 3 RMs ~718 states, 5 RMs ~21,488 states
- Common mistake: not modeling RM spontaneous abort or unreliable network
Distributed Consensus (Raft)
- Variables: currentTerm, votedFor, log, state, votesGranted, msgs
- Safety: at most one leader per term (
ElectionSafety)
- Safety: logs with same index+term are identical (
LogMatching)
- State space: 3 nodes, MaxTerm=2 ~10K-100K states
Saga (Compensating Transactions)
- Variables: stepState, sagaState, compensateIdx
- Safety: steps execute in order, compensations in reverse (
OrderInvariant)
- Safety: no completed steps remain after abort (
CompensationComplete)
- Common mistake: not enforcing reverse compensation order
Distributed Lock with Lease
- Variables: lockHolder, leaseExpiry, clock, nodeState
- Safety: at most one holder (
MutualExclusion)
- Models crash (node loses awareness) and lease expiry
- Common mistake: not distinguishing server-side lock state from node belief
CRDT Convergence (G-Counter)
- Variables: counters (vector per node)
- Safety: counters monotonically non-decreasing
- Liveness: all nodes eventually converge after merge
- Common mistake: merge not commutative, associative, and idempotent
Alternatives Comparison
| Tool |
Best For |
Learning |
Distributed Systems |
Temporal Properties |
| TLA+/PlusCal |
Distributed protocols, consensus |
2-3 weeks |
Excellent |
Native |
| Alloy |
Data models, structural properties |
1-2 weeks |
Adequate |
Limited (Alloy 6) |
| Property-Based Testing |
Implementation correctness |
Hours-days |
With stateful testing |
None |
| XState/Statecharts |
UI workflows, single-process |
Days |
Not applicable |
None |
| Session Types/Scribble |
Communication patterns |
Moderate |
Good (message patterns) |
Implicit |
| TLAPS (proofs) |
Critical certification |
Months |
Excellent |
Full |
Combined Workflow (TLA+ + PBT)
- Write TLA+ spec during DESIGN wave; identify invariants
- Model-check with TLC to verify design
- Implement code during DELIVER wave
- Reuse TLA+ invariants as PBT properties
- PBT verifies implementation conforms to verified design
Architecture Decision Record Template
## Decision: Use TLA+ for [Component Name]
### Context
[Component] implements [protocol] with [N] participants
and [concurrency/distribution characteristics].
### Problem
Informal reasoning about [failure/interleaving scenario]
is insufficient because [reason].
### Decision
Formally specify [component] in TLA+/PlusCal and verify:
- Safety: [specific invariants]
- Liveness: [specific temporal properties]
### Model Parameters
- Nodes: [2-3 for initial verification]
- Messages: [bounded to N]
- Failure modes: [crash, partition, message loss]
### Estimated Effort
- Specification: [1-2 weeks]
- Model checking: [hours to days]
### Not Modeling (out of scope)
- [performance, serialization, UI, etc.]
Architect's Checklist
- Identify components with concurrency, distribution, or complex state machines
- Determine safety properties (what must NEVER happen)
- Determine liveness properties (what must EVENTUALLY happen)
- Estimate model parameters and state space
- Assess cost-effectiveness vs. alternatives (decision tree above)
- Document decision in ADR with specific invariants and properties
- Scope verification: focused specs per subsystem, not one monolith
Industry Precedent
| Organization |
Systems Verified |
Outcome |
| AWS |
14 projects across 10 systems (DynamoDB, S3, EBS) |
Found subtle bugs in every system; management actively encourages adoption |
| Azure Cosmos DB |
All 5 consistency levels |
Specs became authoritative reference, replaced ambiguous docs |
| MongoDB |
Replication, reconfiguration, transactions |
Logless reconfig deployed since 4.4, no protocol bugs |
| Elasticsearch |
Cluster coordination, data replication |
4 TLA+ specs + Isabelle proofs, open-sourced |
| CockroachDB |
Transaction layer |
TLA+ specs in repository under docs/tla-plus/ |
Source: nWave-ai/nWave → nWave/skills/nw-formal-verification-tlaplus/SKILL.md
Also appears in: nWave-ai/nWave/plugins/nw/skills/nw-formal-verification-tlaplus/SKILL.md
1---2name: nw-formal-verification-tlaplus3description: TLA+ and PlusCal for specifying distributed system invariants. Decision heuristics for when formal verification adds value, key patterns, state explosion management, and alternatives comparison.4---567# Formal Verification with TLA+89## When to Recommend Formal Verification1011### Decision Tree1213```14Is the system distributed or concurrent?15|16+-- No --> Complex state machine with high failure cost?17| +-- No --> NOT cost-effective. Use property-based testing.18| +-- Yes --> CONSIDER TLA+19|20+-- Yes --> Consensus, coordination, or distributed transactions?21| +-- Yes --> RECOMMEND TLA+22| +-- No --> Could concurrency bug cause data loss or safety issues?23| +-- Yes --> RECOMMEND TLA+24| +-- No --> OFFER as option25```2627### Strong Indicators (Recommend)2829| Domain | Why TLA+ Adds Value | Evidence |30|--------|-------------------|----------|31| Distributed consensus (Paxos, Raft) | Subtle interleaving bugs in leader election | Raft TLA+ spec ~400 lines, found implementation bugs |32| Financial distributed transactions | Atomicity violations cause monetary loss | AWS DynamoDB replication verified |33| Leader election, distributed locking | Split-brain, deadlock, stale-lock | AWS lock manager verified |34| Eventual consistency / CRDTs | Convergence proofs required | TLA+ CRDT framework verifies SEC |35| Safety-critical state machines | Regulatory requirements | DO-178C, CENELEC recognize formal methods |36| Multi-party coordination (sagas, 2PC) | Compensation ordering, partial failure | 2PC is canonical TLA+ example |37| Data replication protocols | Ordering, consistency under failure | Elasticsearch, MongoDB, Cosmos DB verified |3839### When NOT to Use4041- Simple CRUD (bugs are in implementation, not design)42- Single-process without complex state machines43- Prototypes/MVPs (design will change before verification completes)44- Performance optimization (TLA+ models correctness, not performance)4546### Cost-Benefit Reference4748- Learning curve: 2-3 weeks to useful results (AWS engineers, all levels)49- Typical spec effort: 2-4 weeks part-time for a distributed protocol50- ROI highest when: bug cost is high, system is long-lived, protocol is novel, concurrency testing is impractical5152## Core Concepts for Architects5354### What TLA+ Specifies5556TLA+ describes **what** a system should do (allowed behaviors), not **how** to implement it. Specifications are mathematical objects checked for correctness before any code exists.5758### Safety vs. Liveness5960| Property Type | Meaning | Expression | Example |61|--------------|---------|------------|---------|62| Safety | Nothing bad happens | Invariant: predicate true in every reachable state | "Two processes never hold same lock" |63| Liveness | Something good eventually happens | Temporal: `<>` (eventually), `[]<>` (infinitely often) | "Every request eventually gets response" |6465Safety violations produce counterexample traces (the debugging artifact). Liveness requires fairness conditions.6667### PlusCal vs. Raw TLA+6869PlusCal compiles to TLA+ with programming-like syntax. Start with PlusCal for first 2-3 specs, then learn raw TLA+ for cases PlusCal cannot express.7071Key PlusCal constructs: `variables` (state) | `labels` (atomic action boundaries) | `either/or` (nondeterministic choice) | `await` (blocking) | `process \in 1..N` (concurrent processes) | `fair process` (weak fairness)7273Labels define concurrency granularity: everything between two labels is one atomic step. Two processes interleave only at label boundaries.7475## State Explosion Management7677State space grows exponentially: `(states per node)^(nodes) x (message permutations)`.7879### Containment Strategies8081| Strategy | Technique | Impact |82|----------|-----------|--------|83| Bound parameters | Start with 2-3 nodes, 2-4 messages | Most bugs appear at small N |84| Symmetry reduction | `SYMMETRY Permutations(Nodes)` | Up to N! reduction |85| Reduce labels | Merge labels where fine-grained atomicity unnecessary | Orders of magnitude |86| State constraints | `CONSTRAINT Len(log[n]) < MaxLogLength` | Prune uninteresting states |87| Abstraction | Model protocol not implementation (TCP -> message set) | Dramatic reduction |88| Decomposition | Multiple focused specs, not one monolith | Each independently checkable |89| Progressive refinement | 2 nodes -> 3 nodes -> add failures -> add liveness | Incremental verification |90| Simulation mode | `java -jar tla2tools.jar -simulate -depth 100` | Trades completeness for speed |9192### Memory and Time Budgets9394| Unique States | Expected Time | Memory | Approach |95|--------------|---------------|--------|----------|96| < 10K | Seconds | < 1 GB | Exhaustive, single thread |97| 10K - 1M | Minutes | 1-4 GB | Exhaustive, `-workers auto` |98| 1M - 100M | Hours | 4-32 GB | Exhaustive with constraints |99| 100M - 1B | Days | 32-64 GB | Large instance or simulation |100| > 1B | Weeks | 60+ GB | Simulation, TLAPS, or decompose |101102### Estimation Before Running1031041. Count distinct variable values in model1052. Multiply domains together for baseline1063. Start TLC with smallest parameters, observe state count1074. Extrapolate: doubling a parameter typically squares or cubes the space108109## Key Specification Patterns110111### Two-Phase Commit (2PC)112- Variables: rmState, tmState, tmPrepared, msgs113- Safety: no RM commits while another aborts (`Consistency`)114- State space: 3 RMs ~718 states, 5 RMs ~21,488 states115- Common mistake: not modeling RM spontaneous abort or unreliable network116117### Distributed Consensus (Raft)118- Variables: currentTerm, votedFor, log, state, votesGranted, msgs119- Safety: at most one leader per term (`ElectionSafety`)120- Safety: logs with same index+term are identical (`LogMatching`)121- State space: 3 nodes, MaxTerm=2 ~10K-100K states122123### Saga (Compensating Transactions)124- Variables: stepState, sagaState, compensateIdx125- Safety: steps execute in order, compensations in reverse (`OrderInvariant`)126- Safety: no completed steps remain after abort (`CompensationComplete`)127- Common mistake: not enforcing reverse compensation order128129### Distributed Lock with Lease130- Variables: lockHolder, leaseExpiry, clock, nodeState131- Safety: at most one holder (`MutualExclusion`)132- Models crash (node loses awareness) and lease expiry133- Common mistake: not distinguishing server-side lock state from node belief134135### CRDT Convergence (G-Counter)136- Variables: counters (vector per node)137- Safety: counters monotonically non-decreasing138- Liveness: all nodes eventually converge after merge139- Common mistake: merge not commutative, associative, and idempotent140141## Alternatives Comparison142143| Tool | Best For | Learning | Distributed Systems | Temporal Properties |144|------|----------|----------|--------------------|--------------------|145| TLA+/PlusCal | Distributed protocols, consensus | 2-3 weeks | Excellent | Native |146| Alloy | Data models, structural properties | 1-2 weeks | Adequate | Limited (Alloy 6) |147| Property-Based Testing | Implementation correctness | Hours-days | With stateful testing | None |148| XState/Statecharts | UI workflows, single-process | Days | Not applicable | None |149| Session Types/Scribble | Communication patterns | Moderate | Good (message patterns) | Implicit |150| TLAPS (proofs) | Critical certification | Months | Excellent | Full |151152### Combined Workflow (TLA+ + PBT)1531541. Write TLA+ spec during DESIGN wave; identify invariants1552. Model-check with TLC to verify design1563. Implement code during DELIVER wave1574. Reuse TLA+ invariants as PBT properties1585. PBT verifies implementation conforms to verified design159160## Architecture Decision Record Template161162```markdown163## Decision: Use TLA+ for [Component Name]164165### Context166[Component] implements [protocol] with [N] participants167and [concurrency/distribution characteristics].168169### Problem170Informal reasoning about [failure/interleaving scenario]171is insufficient because [reason].172173### Decision174Formally specify [component] in TLA+/PlusCal and verify:175- Safety: [specific invariants]176- Liveness: [specific temporal properties]177178### Model Parameters179- Nodes: [2-3 for initial verification]180- Messages: [bounded to N]181- Failure modes: [crash, partition, message loss]182183### Estimated Effort184- Specification: [1-2 weeks]185- Model checking: [hours to days]186187### Not Modeling (out of scope)188- [performance, serialization, UI, etc.]189```190191## Architect's Checklist1921931. Identify components with concurrency, distribution, or complex state machines1942. Determine safety properties (what must NEVER happen)1953. Determine liveness properties (what must EVENTUALLY happen)1964. Estimate model parameters and state space1975. Assess cost-effectiveness vs. alternatives (decision tree above)1986. Document decision in ADR with specific invariants and properties1997. Scope verification: focused specs per subsystem, not one monolith200201## Industry Precedent202203| Organization | Systems Verified | Outcome |204|-------------|-----------------|---------|205| AWS | 14 projects across 10 systems (DynamoDB, S3, EBS) | Found subtle bugs in every system; management actively encourages adoption |206| Azure Cosmos DB | All 5 consistency levels | Specs became authoritative reference, replaced ambiguous docs |207| MongoDB | Replication, reconfiguration, transactions | Logless reconfig deployed since 4.4, no protocol bugs |208| Elasticsearch | Cluster coordination, data replication | 4 TLA+ specs + Isabelle proofs, open-sourced |209| CockroachDB | Transaction layer | TLA+ specs in repository under docs/tla-plus/ |210211---212213**Source:** [`nWave-ai/nWave`](https://github.com/nWave-ai/nWave) → `nWave/skills/nw-formal-verification-tlaplus/SKILL.md`214215**Also appears in:** `nWave-ai/nWave/plugins/nw/skills/nw-formal-verification-tlaplus/SKILL.md`