Library / Case Studies

Data Wrangling at Slack

For a company like Slack that strives to be as data-driven as possible, understanding how our users use our product is essential. The Data Engineering team at Slack works to provide an ecosystem to help people in the company quickly and easily answer questions about usage, so they can make better and data informed…

IntermediateDatabases

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

Open original source

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

Learn this case study

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

What you are about to study

Slack explains a real system. You should know the basics: caching, queues and replication.

Ideas you will meet

Databases
Schemas, indexes, query plans and choosing a store.

What we already know about this

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

  • 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

  • Databases Deep Dive · 13 minChoosing a database typeA practical map from workload to database: relational, document, key-value, wide-column, search, graph, time-series and vector stores.Read here

    Start from the access pattern

    There is no best database; there is a best database for a workload. Ask:

    1. What are the main queries (by key, by range, by search, by relationship)?
    2. How much data and how fast does it grow? Read/write ratio?
    3. What consistency and transaction guarantees are needed?
    4. What latency is required, and where are users?
    5. What can your team operate?

    The families

    Figure SDA-DDV-05-1 · Map from need to database family · © forcsguy.com

    Relational (PostgreSQL, MySQL)

    Tables, SQL, joins, constraints, ACID transactions. The default for most business data. PostgreSQL has rich features (JSON, full-text, extensions, many index types); MySQL is widely deployed and simple to operate. They scale vertically very far, and read replicas and sharding extend them. Choose when data is structured, relationships matter and correctness is critical.

    Document (MongoDB and similar)

    Stores JSON-like documents; flexible schema; related data can be embedded in one document so a single read gets everything. Good for content, catalogues and objects read whole. Watch for duplicated data, joins you must do in code, and weaker multi-document transaction habits.

    Key-value (Redis, Memcached; DynamoDB as a key-value/wide hybrid)

    Lookup by key at very low latency. Redis adds data structures (hashes, sorted sets, lists, bitmaps), persistence and clustering (see the Redis lesson). Ideal for caches, sessions, counters, rate limits, leaderboards. Not for ad-hoc queries.

    Wide-column and partitioned key stores (Cassandra, DynamoDB, HBase)

    Data is partitioned by a partition key across many nodes; you design tables around queries. Excellent write throughput, horizontal scale and availability. Cost: limited query flexibility, careful key design (hot partitions), eventual consistency by default. Good for event logs, messaging history, time-ordered user data.

    Search engines (Elasticsearch, OpenSearch, Solr)

    Build an inverted index (word to documents) for full-text search, relevance scoring, filters and facets. Usually a secondary copy of data from a primary database, kept in sync. Not a system of record: treat it as a derived index that can be rebuilt.

    Graph (Neo4j and others)

    Stores nodes and relationships and answers questions that follow connections: friends of friends, fraud rings, recommendations, dependency analysis. Where many-hop traversals would need expensive recursive joins in SQL, a graph database is natural.

    Time-series (InfluxDB, TimescaleDB, Prometheus)

    Optimised for append-heavy, timestamped data with time-range queries, downsampling and retention. Used for metrics, IoT and finance ticks (see the metrics monitoring lesson). Keep tag cardinality low.

    Vector databases (and vector indexes in other databases)

    Store embeddings (arrays of numbers representing meaning) and find the nearest neighbours, using approximate indexes (graph-based or clustering) for speed. Used for semantic search and retrieval for AI applications. Many general databases now offer vector indexes, which can be enough for moderate scale and avoids another system.

    A quick chooser

    NeedFirst choice
    Business data with relationships and transactionsRelational
    Flexible, self-contained recordsDocument
    Cache, session, counter, leaderboardRedis
    Massive write volume, simple access by keyWide-column / DynamoDB-style
    Full-text search and facetsSearch engine
    Many-hop relationship queriesGraph
    Metrics and sensor dataTime-series
    Semantic similarityVector index
    Analytics on large historyWarehouse or lakehouse (see the big data course)

    Polyglot persistence and its price

    Many systems use several stores, each for what it does best: a relational database as the source of truth, a cache, a search index and a metrics store fed from it. The cost is keeping them in sync (change events, outbox pattern, rebuild jobs), more to operate and more failure modes. Add a store only when a measured need justifies it.

    SQL versus NoSQL, honestly

    "NoSQL" is a family of different designs, not one thing. Relational databases scale further than many assume; NoSQL stores often give up joins and some consistency for scale and flexibility. Decide on requirements, not fashion. If in doubt, start relational and specialise later.

    Questions before committing

    • Can we model our top ten queries easily?
    • What happens at 10 times the data? At a regional failure?
    • How do we back up, restore, migrate and monitor it?
    • Does the team know it, and is it supported well on our platform?

    Real-world reading

    Open this lesson with its quiz and exercise

  • System Design Foundations · 11 minChoosing and using a databaseRelational versus NoSQL, what an index really does, and how to decide between them without following fashion.Read here

    The two big families

    Relational databases (PostgreSQL, MySQL) store data in tables with rows and columns, linked by keys. You query them with SQL and can join tables. Their key promise is ACID transactions:

    • Atomicity: a group of changes happens entirely or not at all.
    • Consistency: rules such as foreign keys always hold.
    • Isolation: concurrent transactions do not see each other's half-finished work.
    • Durability: once committed, data survives a crash.

    NoSQL databases is a loose label for stores that give up some relational features for scale or flexibility:

    TypeShapeExamplesGood for
    Key-valuekey maps to a blobRedis, DynamoDBcaches, sessions, huge lookups
    DocumentJSON-like documentsMongoDB, Firestorecontent with varied fields
    Wide-columnrows with flexible columnsCassandra, HBasemassive write volumes, time series
    Graphnodes and edgesNeo4jrelationship-heavy queries

    A quick map from the kind of question you ask to the kind of store that answers it best:

    Figure SDA-FND-04-1 · Which kind of store fits the questions you ask · © forcsguy.com

    A library card catalogue: an index lets you jump straight to the right drawer instead of reading every bookImage: MarkBuckawicki · CC0 · Source · Wikimedia Commons: Wooden Card Catalog Furniture

    Indexes: how reads get fast

    Without an index, finding rows where email = '[email protected]' means reading every row. With an index on email the database keeps a sorted structure (usually a B-tree) and finds the row in a few steps, even among millions.

    Figure SDA-FND-04-2 · Indexed lookup versus full scan · © forcsguy.com

    The trade-off: each index takes space and every write must update it. Index the columns you filter, join and sort on, and do not index everything.

    Useful habits:

    • Look at how the database plans a query (EXPLAIN) before guessing.
    • A composite index on (user_id, created_at) serves queries on user_id alone or on both, but not on created_at alone. Column order matters.
    • Very low-variety columns (like a true/false flag) rarely benefit from an index.

    Where relational databases get strained

    A single relational database handles a lot, but you may hit limits:

    • Read load: add copies that serve reads (lesson 5).
    • Write load or data size: split the data across several databases, called sharding (lesson 5).
    • Shape of data: huge volumes of simple records, or extremely flexible documents, may fit another model better.

    Choosing: ask about the access pattern

    1. What are the most frequent queries? By key, by range, by search, by relationship?
    2. Which guarantees are non-negotiable? Strict consistency for money, or "eventually correct" for like counts?
    3. How big and how fast will it grow?
    4. What does the team already know how to operate?

    A worked example: what an index is worth

    A table holds 100 million orders, and the app asks "show this customer's orders" thousands of times a second.

    • Without an index the database reads every row to find matches: a sequential scan. At, say, 200 bytes a row that is 20 GB read from disk or cache for a single query, taking seconds. Do that 1,000 times a second and the database collapses.
    • With a B-tree index on customer_id the database walks a shallow tree. A page holds a few hundred keys, so 100 million rows need only about 4 levels: root, two internal levels, a leaf. That is roughly 4 page reads to find the row locations, then a few more to fetch the rows. Most of the upper levels live in memory, so the real cost is one or two disk reads, in milliseconds.

    The price: every index must be updated on every insert, update and delete. A table with 5 indexes turns one logical insert into about 6 physical writes, and the indexes take space (often as much as the table). So index what your queries actually filter, join and sort on, and not much else.

    Figure SDA-FND-04-3 · Finding one row among a hundred million with a B-tree · © forcsguy.com

    What a transaction does for you

    A transaction groups several changes so they succeed or fail together. A transfer of 100 from account A to account B is two updates, and it must never be applied halfway. Relational databases give transactions the ACID properties:

    • Atomic: all of it happens or none of it.
    • Consistent: rules such as "balance never negative" are enforced.
    • Isolated: concurrent transactions do not see each other's half-finished work (to a degree you choose).
    • Durable: once the database says "committed", the change survives a crash.

    Durability comes from the write-ahead log (WAL): before changing the data pages, the database appends the change to a log and forces it to disk. If the machine crashes, restart replays the log and the committed work reappears.

    Figure SDA-FND-04-4 · Why a committed write survives a crash · © forcsguy.com

    You can build a toy version in the write-ahead log lab.

    Mistakes people make

    • No index on the column you filter by, especially foreign keys. Use EXPLAIN to see whether a query scans.
    • Too many indexes. Each one slows writes and uses memory. Drop the ones nobody uses.
    • The N+1 query. Loading 100 orders and then running one query per order for its items is 101 round trips. Load them together with a join or a single IN query.
    • Money as floating point. Use integers (cents) or exact decimals.
    • Choosing NoSQL to avoid thinking about schema. If your data is relational, you will rebuild joins and constraints by hand, badly.
    • Treating the database as a queue or a log. Polling a hot table for work is a common cause of lock contention (see the SKIP LOCKED lesson for doing it properly).
    • Never testing a restore. A backup you have not restored is a hope, not a backup.

    Try it yourself

    Open the indexes in depth lesson and the query optimisation lesson next. In the System Builder, see how much load a cache and replicas take off a single database.

    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 Data Wrangling at Slack.

  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…