Database Distributed Systems · Lesson 102 of 112

Database Why Distribute Data

What you will learn

  • The four main reasons to distribute a database over several machines
  • The costs: the network is slow and unreliable, and machines fail separately
  • What partial failure means and why a lost reply is dangerous
  • Why retried requests need to be idempotent
  • The map of this chapter: replication, partitioning, consistency, CAP, transactions, consensus

Every example in this chapter is a simulation: a few lines of Python that imitate one idea so you can see it work. They are not real databases, and real systems add many details. The aim is to understand the ideas that real systems are built on.

1. One machine is simple, and it has limits

So far in this course, one database lived on one machine. That is a good design when it is enough: there is one copy of the data, one place to look, and the transactions of chapter 6 work without extra tricks.

Sooner or later a single machine can run into a limit. A distributed database keeps data on several machines (nodes) that cooperate over a network, and it is usually chosen for one of four reasons:

Reason The problem How several machines help
Capacity the data no longer fits on one machine's disk each machine holds a part (lesson 14.3)
Throughput one machine cannot answer all the requests several machines share the work
Availability if the one machine fails, everything stops another copy takes over (lesson 14.2)
Closeness users far away wait for every request to cross the world keep a copy near each group of users

Notice that the first two are about size and the last two about safety and speed. Spreading data is a tool for specific problems, not a goal in itself.

2. Availability, in numbers

Why does a second copy help? Suppose, as an assumption, that each machine is up 99% of the time. If we need only one of several copies to be up, the chance that all are down at once is small:

p_up = 0.99                      # an assumption: each machine is up 99% of the time
for n in (1, 2, 3):
    p_all_down = (1 - p_up) ** n  # all n machines down at once (only if failures are independent)
    print(n, "machine(s): chance at least one is up =", round(1 - p_all_down, 6))
1 machine(s): chance at least one is up = 0.99
2 machine(s): chance at least one is up = 0.9999
3 machine(s): chance at least one is up = 0.999999

The same arithmetic in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A recursive query multiplies the chance that a machine is down once per extra machine:

WITH RECURSIVE m(n, p_all_down) AS (
  SELECT 1, 0.01
  UNION ALL SELECT n + 1, p_all_down * 0.01 FROM m WHERE n < 3
)
SELECT n AS machines, ROUND(1 - p_all_down, 6) AS chance_at_least_one_is_up FROM m;
machines  chance_at_least_one_is_up
--------  -------------------------
       1                       0.99
       2                     0.9999
       3                   0.999999
(3 rows)
WITH RECURSIVE m(n, p_all_down) AS (
  SELECT 1, 0.01
  UNION ALL SELECT n + 1, p_all_down * 0.01 FROM m WHERE n < 3
)
SELECT n AS machines, ROUND(1 - p_all_down, 6) AS chance_at_least_one_is_up FROM m;
machines  chance_at_least_one_is_up
--------  -------------------------
       1                       0.99
       2                     0.9999
       3                   0.999999
(3 rows)
WITH RECURSIVE m(n, p_all_down) AS (
  SELECT 1, 0.01
  UNION ALL SELECT n + 1, p_all_down * 0.01 FROM m WHERE n < 3
)
SELECT n AS machines, ROUND(1 - p_all_down, 6) AS chance_at_least_one_is_up FROM m;
machines  chance_at_least_one_is_up
--------  -------------------------
       1                       0.99
       2                     0.9999
       3                   0.999999
(3 rows)

Three copies take us from "down about 1% of the time" to "down about 0.0001% of the time". Be careful with this arithmetic: it assumes the machines fail independently. Real failures are often correlated: two machines in the same building share a power supply, and one bad software update can hit every machine at once. The numbers show the idea, not a promise.

Quick check: why can three copies still all fail together?

Because failures are not always independent. A shared power cut, a shared network switch, or the same bug installed on all three can take them down at the same moment.

3. The costs

Distribution is not free. Three costs explain almost everything in this chapter.

  1. The network is slow. Talking to another machine takes far longer than reading memory on your own machine, and the farther away the machine, the longer it takes.
  2. The network is unreliable. A message can be lost, delayed, duplicated or delivered out of order.
  3. Partial failure. On one machine, a crash stops everything, so you know what happened. In a distributed system some machines can fail while others carry on, and the caller often cannot tell which situation it is in.

The third cost is the nastiest. When you send a request and hear nothing back, you do not know whether

  • the request never arrived,
  • the request arrived and was done, but the reply was lost, or
  • the machine is just slow.

From the caller's side these three look exactly the same: silence.

4. Silence and retries

The natural reaction to silence is to try again. Here is a simulation of a client that deposits 50 into an account that holds 100 (so the correct final balance is 150). Each call loses its request or its reply with some probability. The random numbers use a fixed seed, so the "random" losses repeat every time you run it.

import random

random.seed(7)                       # fixed seed so the "random" losses repeat every run


def deposit(account, amount, request_id, applied):
    """One network call to a server (a simulation). Returns True only if the client sees the reply."""
    if random.random() < 0.4:        # the request is lost on the way: the server never sees it
        return False
    if request_id not in applied:    # the server applies the request...
        applied.add(request_id)
        account["balance"] += amount
    return random.random() >= 0.4    # ...but the reply may be lost on the way back


def client(account, use_request_id):
    applied = set()
    for attempt in range(1, 6):
        rid = "req-1" if use_request_id else f"req-{attempt}"   # the same id on every retry, or a new one
        if deposit(account, 50, rid, applied):
            return attempt
    return None


for label, same_id in (("retry with a NEW id each time ", False), ("retry with the SAME id        ", True)):
    results = []
    for trial in range(6):
        account = {"balance": 100}
        client(account, same_id)
        results.append(account["balance"])
    print(label, "-> final balances:", results, " (correct is 150)")
retry with a NEW id each time  -> final balances: [200, 250, 150, 250, 200, 200]  (correct is 150)
retry with the SAME id         -> final balances: [150, 150, 150, 150, 150, 150]  (correct is 150)

Idempotent requests in SQL. The server's memory of request ids is a table with the id as its primary key, and INSERT OR IGNORE does nothing when the id is already there. The wallet and applied_requests tables are small ones of their own; Reset data removes them. The client sends request req-1 three times (the replies were "lost"), and the balance changes only once:

CREATE TABLE wallet (balance INTEGER NOT NULL);
CREATE TABLE applied_requests (request_id TEXT PRIMARY KEY);
INSERT INTO wallet VALUES (100);
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
SELECT balance FROM wallet;
balance
-------
    150
(1 row)

With a new id on every retry the same three sends deposit three times:

UPDATE wallet SET balance = 100;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-2');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-3');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
SELECT balance FROM wallet;
balance
-------
    250
(1 row)
CREATE TABLE wallet (balance INTEGER NOT NULL);
CREATE TABLE applied_requests (request_id TEXT PRIMARY KEY);
INSERT INTO wallet VALUES (100);
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
SELECT balance FROM wallet;
balance
-------
    150
(1 row)

With a new id on every retry the same three sends deposit three times:

UPDATE wallet SET balance = 100;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-2');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-3');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
SELECT balance FROM wallet;
balance
-------
    250
(1 row)
CREATE TABLE wallet (balance INTEGER NOT NULL);
CREATE TABLE applied_requests (request_id TEXT PRIMARY KEY);
INSERT INTO wallet VALUES (100);
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('req-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
SELECT balance FROM wallet;
balance
-------
    150
(1 row)

With a new id on every retry the same three sends deposit three times:

UPDATE wallet SET balance = 100;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-1');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-2');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
BEGIN;
INSERT OR IGNORE INTO applied_requests VALUES ('a-3');
UPDATE wallet SET balance = balance + 50 WHERE changes() = 1;
COMMIT;
SELECT balance FROM wallet;
balance
-------
    250
(1 row)

Look at the first line. When the client retries with a new request each time, a lost reply makes it deposit again, so the balance can be 200 or even 250. With the same request id on every retry, the server recognises that it already applied that request and ignores the repeat, so the balance is always 150.

A request that can safely be repeated without changing the result more than once is called idempotent. Giving each request a unique id that the server remembers is a common way to make a non-idempotent action, such as "add 50", behave idempotently. The same idea is behind the transaction patterns of lesson 14.6.

5. The map of this chapter

Lesson Question it answers
14.2 Replication how do we keep several copies of the same data?
14.3 Partitioning how do we split data that is too big for one machine?
14.4 Consistency what may a reader see when copies disagree for a moment?
14.5 CAP and PACELC what must we give up when the network breaks, or even when it does not?
14.6 Distributed transactions how do we change data on several machines "all or nothing"?
14.7 Consensus how do machines agree on one leader or one answer, despite failures?

Worked example: should this shop distribute its data?

A small online shop has 20,000 orders, about 5 requests a second at the busiest time, and one machine that is up almost always. A friend suggests "putting the database on five servers in three countries".

Reason Does the shop have the problem?
Capacity no: 20,000 orders fit easily on one disk
Throughput no: 5 requests a second is small for one machine
Availability partly: a nightly backup and a standby copy (lesson 12.5) may be enough
Closeness no: nearly all customers are in one city

The shop would take on all the costs of this chapter (network failures, consistency questions, harder transactions) for almost no gain. One database plus a backup and perhaps one standby copy is the better answer. The numbers are made up.

Common mistakes

  • Distributing too early. Splitting a database makes everything harder; do it only for a real capacity, throughput, availability or distance problem.
  • Believing independent failures. Copies in the same building, the same power feed or running the same software can fail together.
  • Treating silence as failure. A missing reply does not prove the request was not done.
  • Retrying a non-idempotent request blindly. It can apply the same change twice.

Key takeaways

  • A distributed database keeps data on several machines for capacity, throughput, availability or closeness to users.
  • The costs are a slow, unreliable network and partial failure: part of the system can fail while the rest runs.
  • A caller cannot tell a lost request from a lost reply from a slow machine.
  • Retrying is safe only for idempotent requests, for example by sending the same request id every time.
  • Do not distribute data unless you have a real problem that one machine cannot solve.

Practice

1. Name the four reasons to distribute a database.

Show answer

Capacity (more data than one machine holds), throughput (more requests than one machine handles), availability (survive a machine failing) and closeness (copies near the users).

2. If each machine is up 99% of the time and failures are independent, what is the chance that at least one of two copies is up?

Show answer

1 − 0.01 × 0.01 = 0.9999, or 99.99%. This holds only if the two machines fail independently.

3. A client sends "add 50" and gets no reply. Give two different things that may have happened.

Show answer

The request may have been lost and never applied, or it may have been applied and only the reply lost (or the server may simply be slow). The client cannot tell which.

4. Why did the balance in the simulation sometimes become 200 or 250?

Show answer

When a reply was lost, the client retried with a new request id, so the server treated the retry as a new deposit and applied it again.

5. What does "idempotent" mean, and how did the same request id help?

Show answer

An idempotent request can be repeated without changing the result beyond the first time. Because the server remembered each request id, a repeat with the same id was ignored.

6. A school with 800 students and one machine that is rarely down wants a five-country database. What would you tell them?

Show answer

They do not have a capacity, throughput or distance problem, and distribution adds network failures and consistency problems. A good backup, and perhaps a standby copy for availability, is enough.