Library / Blogs

ClickHouse Blog

Learn about the latest ClickHouse tips, tricks and company announcements.

By ClickHouse engineers · ClickHouse · Added 2026-10-12

Open original source

All content belongs to ClickHouse engineers / ClickHouse. We only link to it and give credit. Report a problem

Learn this article

About 37 min left. Your work is saved as you go.

What you are about to study

ClickHouse wrote this to explain how they thought about a problem. You should know the basics: caching, queues and replication.

Ideas you will meet

Databases
Schemas, indexes, query plans and choosing a store.
Storage Engines
Write-ahead logs, B-trees and LSM-trees.

What we already know about this

Our own lessons on these ideas. Read them here before you start, so it makes sense.

  • Software Design Essentials · 11 minClean and hexagonal architectureKeep business rules independent of frameworks, databases and the web: the dependency rule, layers, and ports and adapters.Read here

    The problem

    In many applications, business rules are tangled with framework code, SQL and HTTP details. Then:

    • You cannot test a rule without a database and a web server.
    • Changing a framework or database means rewriting business logic.
    • The code is organised around technology, not around what the system does.

    Several architectures (hexagonal, onion, clean) solve this with the same idea: put business rules at the centre and keep details at the edges.

    The dependency rule

    Figure SDA-SDE-06-1 · Clean architecture: dependencies point inwards · © forcsguy.com

    Source code dependencies point inwards only. Entities know nothing about use cases; use cases know nothing about the web or the database. Outer layers depend on inner ones, never the reverse.

    LayerContainsKnows about
    EntitiesCore business objects and rules that would exist whatever the technologyNothing else
    Use casesApplication-specific actions ("place order", "cancel subscription") that coordinate entitiesEntities and the ports they define
    Interface adaptersControllers, presenters, repositories' implementations, mappersUse cases
    Frameworks and driversThe web framework, database, message queue, UIAdapters

    Before: logic tangled in the controller

    After: business rules in the middle

    What changed

    • Business rules can be tested without a web server or database
    • The database or framework can be replaced at the edge
    • There are more files and layers to maintain

    Ports and adapters (hexagonal)

    The application is the hexagon. It talks to the outside only through ports: interfaces it owns. Adapters translate between the outside world and the ports.

    • Driving (inbound) ports: how the world calls the application (PlaceOrder). Adapters: REST controller, CLI, message listener, test.
    • Driven (outbound) ports: what the application needs (OrderRepository, PaymentGateway, Clock). Adapters: SQL implementation, payment provider client, fake for tests.
    // Port owned by the application
    interface OrderRepository { save(order: Order): Promise<void>; byId(id: string): Promise<Order | null> }
    interface PaymentGateway { charge(cents: number, token: string): Promise<boolean> }
    
    // Use case: pure application logic
    class PlaceOrder {
      constructor(private orders: OrderRepository, private payments: PaymentGateway) {}
      async run(input: { items: Item[]; token: string }) {
        const order = Order.create(input.items);                   // entity enforces rules
        if (!(await this.payments.charge(order.totalCents, input.token))) throw new Error("Payment failed");
        await this.orders.save(order);
        return order.id;
      }
    }
    
    // Adapters live outside, implementing the ports
    class SqlOrderRepository implements OrderRepository { /* uses a database */ }
    class StripeGateway implements PaymentGateway { /* calls the provider */ }
    
    // Composition root wires everything together at start-up
    const placeOrder = new PlaceOrder(new SqlOrderRepository(db), new StripeGateway(key));
    

    This is the dependency inversion principle from SOLID applied to a whole system.

    Benefits

    • Testable: run use cases with in-memory fakes, fast and without infrastructure.
    • Replaceable details: change the database, queue or web framework by writing an adapter.
    • Focus on the domain: the central code reads like the business process.
    • Deferred decisions: you can postpone choosing a database.

    Costs and cautions

    • More structure: interfaces, mappers and wiring add code. For a small CRUD app it can be overkill.
    • Mapping between layers (domain objects, database rows, API shapes) is repetitive; do it deliberately and avoid leaking database entities into the API.
    • Do not create layers "because the diagram says so". Add a boundary where a real change or testing need exists.
    • It is about dependencies, not folder names: a good folder layout helps but does not guarantee the rule is followed. Enforce it with tests or lint rules.
    • Domain-driven design supplies the language for the centre of the hexagon (next lesson).
    • Microservices are a deployment choice; each service can use this internal structure.
    • Composition root: one place, at start-up, where concrete classes are chosen and injected.

    Real-world reading

    Open this lesson with its quiz and exercise

  • Advanced Distributed Systems · 13 minWrite-ahead logs, B-trees and LSM-treesHow databases make writes durable and fast: the log first, then two ways of organising data on disk and the trade-offs between them.Read here

    Durability needs a log

    A database holds data in memory pages for speed, but memory is lost on a crash. To be durable it must put a record of every change on disk before it tells the client "committed". That record is the write-ahead log (WAL): an append-only file of changes.

    Figure SDA-ADS-02-1 · Write-ahead log flow · © forcsguy.com

    The same idea appears everywhere: databases, file systems (journaling), message brokers (the log is the data) and replication (followers replay the primary's log).

    Two ways to organise data on disk

    B-trees: update in place

    A B-tree keeps sorted keys in fixed-size pages arranged as a shallow tree. Finding a key takes a few page reads; changing a key updates a page in place (plus a WAL record for safety).

    • Strengths: predictable reads, efficient range scans, mature, used by most relational databases.
    • Costs: writes touch random pages (random I/O); page splits and fragmentation; every write is written twice (WAL and page).

    LSM-trees: append and merge

    A log-structured merge tree buffers writes in a sorted in-memory table (the memtable), also logged to a WAL. When full, it is flushed as an immutable sorted file (an SSTable). Background compaction merges files and discards overwritten and deleted values.

    Figure SDA-ADS-02-2 · LSM-tree write and read path · © forcsguy.com

    • Strengths: very fast sequential writes, good compression, high write throughput.
    • Costs: a read may check several files (helped by bloom filters and caches); background compaction creates write amplification and I/O spikes; deletes leave tombstones until compaction.

    Choosing

    QuestionB-treeLSM-tree
    Write-heavy ingestionSlowerFaster
    Point reads and range scansSteadyGood, depends on compaction
    Predictable latencyEasierCompaction can add tail latency
    Space usageSome fragmentationTemporary extra during compaction
    Typical usersPostgreSQL, MySQL (InnoDB)Cassandra, RocksDB, HBase, many time-series stores

    There is no winner: choose by workload, and measure. This lesson explains why a store behaves the way it does under load, which helps when diagnosing slow writes or sudden I/O spikes.

    • Checkpoints and snapshots bound recovery time.
    • Replication often ships the WAL to replicas.
    • Fsync policy (flush every write, or every few milliseconds) is a durability versus speed knob.
    • Bloom filters appear in the probabilistic-structures lesson of the core-concepts course.

    Real-world reading

    Open this lesson with its quiz and exercise

  • Databases Deep Dive · 12 minReplication topologies and multi-region databasesSingle-leader, multi-leader and leaderless replication, how they handle conflicts and lag, and what changes across regions.Read here

    Why replicate

    Replication keeps copies of data on several machines for three reasons: availability (survive a node failure), read scaling (serve reads from replicas) and latency (put data near users). The hard part is keeping copies consistent while writes continue. (Basics are in the replication and sharding lesson of the foundations course; this lesson compares the topologies.)

    Single-leader (primary and replicas)

    One node, the leader (primary or master), accepts writes and ships its changes to followers (replicas), which serve reads.

    Figure SDA-DDV-04-1 · Single-leader replication · © forcsguy.com

    • Synchronous replication waits for a follower before acknowledging: safer, slower, and a stalled follower can block writes. Asynchronous is faster but a failover can lose the latest writes. A common compromise: one synchronous follower, others asynchronous.
    • Failover must detect failure, choose the most up-to-date replica, redirect clients and ensure the old leader does not come back believing it still leads (split brain).
    • Replication lag causes stale reads. Techniques: read-your-writes (route a user's reads to the leader shortly after they write), monotonic reads (keep a user on one replica), and checking replica position.

    Multi-leader

    Several nodes accept writes (often one per region) and replicate to each other. Benefits: local write latency and continued operation if a region is cut off. Cost: write conflicts.

    Conflict handling options:

    • Avoid them: route all writes for one record to one leader (for example by user or region).
    • Last write wins by timestamp: simple, but silently drops one of two concurrent updates and depends on clocks.
    • Merge values (union of sets, counters) using mergeable data types (CRDTs; see the collaborative editing lesson).
    • Custom resolution in application code, or ask the user.

    Multi-leader also appears in offline-capable apps (each device is a leader) and collaborative editing.

    Before: single leader

    After: multi-leader across regions

    What changed

    • Users in each region write to a nearby database
    • Concurrent edits to the same row need conflict handling
    • More moving parts to run and monitor

    Leaderless (Dynamo-style)

    Any replica accepts writes; clients write to several replicas and read from several, using quorums (W + R > N) to get fresh data (see the key-value store lesson). Background anti-entropy and read repair fix stale copies; versions or vector clocks detect conflicts. It favours availability and is typical of Cassandra and DynamoDB-style stores.

    Figure SDA-DDV-04-2 · Choosing a replication model · © forcsguy.com

    Multi-region designs

    • Active-passive: one region serves writes; another is a warm standby. Simple; failover loses a little data (the replication lag) and takes minutes.
    • Active-active: several regions serve traffic. Requires either partitioning data by home region (each record has one home, cross-region reads are replicas) or true multi-leader conflict handling.
    • Global databases use consensus across regions (see the consensus lesson) for strong consistency at the cost of cross-region write latency; some offer tunable consistency per query.
    • Latency numbers matter: a cross-ocean round trip is around 100 ms or more, so synchronous cross-region replication adds that to every write.
    • Data residency laws may require keeping certain users' data in a region.

    Partitioning and replication together

    Real systems shard data into partitions and replicate each partition (a leader per partition spreads write load across nodes). Rebalancing, hot partitions and cross-partition transactions are the new problems (see sharding and the consistent-hashing lesson).

    Master/slave naming

    You will see "master/slave", "primary/replica" and "leader/follower" for the same single-leader idea; most current documentation prefers the last two.

    Checklist

    • What happens to writes if the leader or a region is lost, and how long?
    • How much data can we lose (RPO) and how long can we be down (RTO)?
    • How do we handle stale reads from replicas?
    • Who resolves conflicts, and how?
    • Have we practised failover?

    Real-world reading

    Open this lesson with its quiz and exercise

Go deeper on this

A path through videos, articles, other case studies and code on the same ideas as ClickHouse Blog.

  1. Warm upGet the vocabulary first.

  2. WatchHow others solve the same problem, on video.

    Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)

  3. ReadEngineers explain it in their own words.

  4. See it in another companyThe same ideas, a different system.

  5. Read the codeSee how it looks when it is real.

Keep learning

Loading community…