High-Level Design Tutorial 0/42 lessons ~6 min read Lesson 25

    Consistency Models

    Consistency models define what readers observe after writes in distributed systems — from strong linearizability to eventual consistency.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Consistency models define what readers observe after writes in distributed systems — from strong linearizability to eventual consistency. HLD interviews use consistency language precisely: strong for bank balances, eventual for social likes, causal for comment threads, read-your-writes for user sessions.

    Consistency is not binary — many systems offer tunable levels per operation. The model must match user-visible requirements and failure behavior, not theoretical purity.

    This lesson maps models to mechanisms and interview explanations.

    Understanding the topic

    Key concepts

    • Strong/linearizable: read sees latest completed write cluster-wide.
    • Sequential consistency: all see same order, not necessarily real-time.
    • Causal: related operations respect cause-effect; unrelated may reorder.
    • Read-your-writes: user sees own updates — session stickiness or version tokens.
    • Eventual: replicas converge without guarantee when.
    • Monotonic reads: no going backward in time on subsequent reads.
    text
    flowchart LR
    Strong --> CP
    Eventual --> AP

    Internal architecture

    Architecture overview

    text
    flowchart LR
    Strong --> CP
    Eventual --> AP

    Step-by-step explanation

    1. Money transfer: sync replication + read from primary — linearizable.
    2. Product catalog: replica reads with 30s staleness OK + cache TTL.
    3. Session service: sticky routing or userId version in token for read-your-writes.
    4. Global social feed: per-region AP with conflict-free replicated data types (CRDT) for counters.
    5. Version vector on comments for causal ordering display.
    6. Explicit consistency knob in API: ?consistency=strong query param for admin.

    Informative example

    Read-your-writes using session token stored in Redis after profile update:

    java
    @Service
    public class ProfileService {
    private final ProfileRepository db;
    private final StringRedisTemplate redis;
    public ProfileService(ProfileRepository db, StringRedisTemplate redis) {
    this.db = db;
    this.redis = redis;
    }
    @Transactional
    public Profile update(String userId, UpdateProfileRequest req) {
    Profile saved = db.save(Profile.merge(userId, req));
    redis.opsForValue().set("profile:version:" + userId,
    String.valueOf(saved.version()), Duration.ofMinutes(30));
    return saved;
    }
    public Profile get(String userId, Optional<Long> clientVersion) {
    Long required = clientVersion.orElse(null);
    String minVersion = redis.opsForValue().get("profile:version:" + userId);
    if (required != null && minVersion != null && required < Long.parseLong(minVersion)) {
    return db.findByIdPrimary(userId); // force fresh read from primary
    }
    return db.findById(userId).orElseThrow();
    }
    }

    Explain trade-off aloud in interviews. Not every feature needs strongest model.

    Real-world use

    Real-world use cases

    • Banking: strong consistency on ledger; eventual on marketing segments.
    • E-commerce inventory: linearizable reserve during checkout window.
    • Social: eventual follower counts; causal for threaded replies.
    • Healthcare vitals dashboard: monotonic reads for clinician session.

    Best practices

    • Document per-feature consistency SLO in architecture docs.
    • Use primary reads sparingly — bottleneck; session tokens smarter.
    • CRDTs for counters and sets where commutative updates OK.
    • Test replica lag impact on UX acceptance tests.
    • Communicate staleness in UI where product allows ('counts may delay').
    • Align cache TTL with consistency promises.

    Common mistakes

    • Claiming strong consistency while reading async replicas.
    • One global model for entire heterogeneous system.
    • Ignoring client-side cached data breaking read-your-writes.
    • Confusing DB isolation (READ COMMITTED) with distributed consistency.
    • No conflict resolution plan for multi-master writes.

    Advanced interview questions

    Q1BeginnerWhat is eventual consistency?
    Replicas may temporarily diverge but converge if writes stop; no immediate global agreement.
    Q2BeginnerWhen need strong consistency?
    Financial transfers, inventory reservation, unique username registration — correctness over availability.
    Q3IntermediateWhat is read-your-writes?
    After user writes, their subsequent reads reflect that write — via sticky session or version check.
    Q4IntermediateCausal vs sequential consistency?
    Causal preserves cause-effect chains; sequential gives global order but allows stale reads relative to real time.
    Q5AdvancedConsistency design for global document editor.
    Operational transform or CRDT for concurrent edits, causal metadata per operation, periodic snapshot to S3, strong consistency for permission ACL changes on primary.

    Summary

    Consistency models specify visible ordering of reads and writes. Match model strength to business tolerance for staleness. Strong for money; eventual for social metrics is common split. Read-your-writes solved with tokens, stickiness, or primary reads. CAP and consistency models together guide store selection. Distributed transactions coordinate consistency across services.

    Ready to mark this lesson complete?Track your journey across the entire course.