SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Relational Databases
  • Document Databases
  • Key-Value Databases
  • Full-Text Search Engines
  • Wide Column Databases
  • Time Series Databases
  • Graph Databases
  • Vector Databases
  • NewSQL Databases
  • Columnar Databases
  • In-Memory Databases
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Types (Deep Dive)

In-Memory Databases

Keep the data in RAM for microsecond answers, and decide how to survive a restart.

โฑ 12 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An in-memory database keeps its data in RAM instead of on a disk. RAM answers in microseconds, many times faster than even a fast disk.

  • Reads and writes do not wait for the disk, so they are extremely quick.
  • But RAM is costly and forgetful: when the power goes, whatever is only in RAM is gone.
  • So you choose a durability plan: snapshots, a log on disk, copies on other machines, or nothing at all (a pure cache).
  • Each plan trades safety against speed.

02Concept: What is it?

A normal database keeps the real data on disk and uses a bit of RAM as a helper (a buffer cache). An in-memory database flips this: RAM is the main home of the data. The structures can be designed for RAM, with no need to arrange data in disk pages, so lookups are very short.

The big question is: what happens when the machine restarts? RAM is wiped. There are four common answers:

  • Nothing. The data is a copy of something stored elsewhere, so you can rebuild it. This is a cache.
  • Snapshots. Every so often, write the whole dataset to disk. After a crash you lose what changed since the last snapshot.
  • A log. Append every change to a file on disk (like a write-ahead log). After a crash, replay the log. You choose how often to force it to disk, once a second or on every write.
  • Replicas. Copy changes to other machines, so a failure of one machine does not lose the data.
Where the data lives
Disk-based database
๐Ÿ“จQuery
โ†“often
๐Ÿ’ฝDiskreal data (slow)
โšกRAM buffera helper
In-memory database
๐Ÿ“จQuery
โ†“always
โšกRAMreal data (fast)
โ‡ฃlog or snapshot
๐Ÿ’ฝDiskonly for recovery
Reads come from RAM. The disk only exists to survive a restart.
๐Ÿง Fast does not mean unsafe, but safe costs speed
An in-memory database can be very durable. The more often you force data to disk, or the more copies you wait for, the safer it is and the slower each write becomes.

03Real-Life Example

๐ŸตThe Whiteboard and the Notebook
A team keeps its work plan on a whiteboard. Anyone can read or change it in a second, which is brilliant. But the board is small, and if someone wipes it, the plan is gone. So the team uses a notebook as a backup. Option 1: take a photo of the board every 30 minutes (a snapshot). Option 2: every time someone changes the board, they also write the change in the notebook (a log). Option 3: a second whiteboard in another room that copies each change (a replica). Option 4: do nothing, because the plan can be rebuilt from emails (a cache).
Whiteboard and notebook
In-memory database
The whiteboard
RAM: fast and easy to change, but it can be wiped
The notebook
Disk: slower, but it survives
A photo every 30 minutes
A snapshot: you lose changes since the last one
Writing each change in the notebook
An append-only log or write-ahead log
Writing it down at once vs at the end of the minute
Flush on every write vs flush every second
A second whiteboard in another room
A replica on another machine
Rebuilding from emails
A cache that can be refilled from the main database
The durability dial
๐ŸงฝNothingall lost
โ†’โ†“
๐Ÿ“ธSnapshotslose minutes
โ†’โ†“
๐Ÿ““Log, per secondlose a second
โ†’โ†“
๐Ÿ”’Log, per writelose nothing
Moving right makes a crash cheaper to survive and each write more expensive.

04Why Do We Need It?

โšกMicrosecond latency
No disk read on the hot path, so answers come back extremely fast.
๐Ÿ”ฅHigh throughput
Simple structures in RAM serve a great number of requests per second per machine.
๐Ÿ›ก๏ธProtect the main database
Used as a cache, it absorbs most reads before they reach the slower store.
๐ŸงฎReal-time work
Leaderboards, counters, sessions and rate limits need fast, frequent updates.
๐Ÿง Fast analytics on hot data
Some in-memory engines run queries over data held fully in RAM.
๐ŸงฉSimple design
Without disk pages to manage, data structures can be simpler and quicker.
When milliseconds matter and the data fits in memory, keep it in memory.

05Where Do We Use It?

๐Ÿ—ƒ๏ธCaches
Keep popular results close to the app, in front of a slower database.
๐Ÿ”‘Sessions
Login sessions looked up on every request.
๐Ÿ†Leaderboards
Sorted scores updated and read all the time.
๐ŸšฆRate limits and counters
Count requests per user per minute, very fast.
๐Ÿ’นTrading and bidding
Systems where a few milliseconds change the outcome.
๐Ÿ“กReal-time features
Presence, live dashboards and message queues in memory.
๐Ÿ“Note
Examples include Redis, Memcached, Aerospike, VoltDB, SingleStore and SAP HANA. Some are mainly caches, and some are used as the main database. Check each product's durability options.

06Types / Parts / How It Works

Ways to survive a restart

PlanHow it worksYou can loseCost
None (cache only)Data lives only in RAMEverything on restartFastest. Needs a source to refill from.
SnapshotsWrite the whole dataset to disk every N seconds or minutesChanges since the last snapshotLow per write, but a snapshot uses CPU and disk
Log, flush every secondAppend each change to a log, force it to disk once a secondAbout one second of writesSmall slowdown
Log, flush every writeForce every change to disk before saying doneNothing that was acknowledgedMuch slower writes
ReplicationSend each change to another machine (asynchronous or waiting for it)Changes the follower did not receive yet (async)Network and an extra machine
Snapshot + log togetherUse the snapshot as a base and the log for what came afterDepends on the log flush settingFaster restart, more files to manage
Snapshot plus log
๐Ÿ“ธSnapshotstate at 10:00
โ†’โ†“+
๐Ÿ““Logchanges after 10:00
โ†’โ†“replay
โšกRAM againback to the crash moment
Base copy Changes since Restored
After a crash: load the last snapshot, then replay the log written after it.

The capacity limit

Everything must fit in RAM (or in the RAM of the whole cluster). When it does not, you either evict old data (fine for a cache), shard across more machines, or move cold data to a cheaper store.

Illustrative cost per GBRAM: highest
Illustrative cost per GBSSD: middle
Illustrative cost per GBHard disk: lowest
VisualizerPull the plug: how much data survives a crash?Pick a persistence plan, choose when the crash happens, then press Crash. Try a longer snapshot gap, a log flushed every second, and an asynchronous follower.
How is the data saved?
Cyan = the server is running. The white line is where the crash will happen.
0 s60 s120 s
Purple lines mark the snapshots.
Relative write speed (illustrative)95% of an unsaved server
Lost in this crash
?
press Crash
Worst-case window
30 s
at most this much
Write speed
95%
illustrative
The server takes 1000 writes per second. Press Crash to pull the plug at second 47.5 and see what comes back after the restart.

A simplified model with a steady, fixed write stream and no random numbers. The write speeds and the 0.5 s follower lag are illustrative: real speed depends heavily on the disk, and real products add more options.

07How to Use It / Steps / Implementation

Using an in-memory database well

  1. 1
    Decide its role
    Is it a cache (can be lost and rebuilt), or the system of record (must not lose acknowledged writes)? This one choice drives everything else.
  2. 2
    Pick the durability level
    Cache: none. Important data: a log flushed every second or on every write, plus replicas. Match the setting to how much loss you can accept.
  3. 3
    Size the memory
    Estimate data size plus overhead per key, plus room for snapshots and growth. Leave headroom: running at the limit leads to evictions or crashes.
  4. 4
    Set an eviction rule
    For a cache, choose a rule such as least recently used, and give keys a time to live, so memory does not fill up.
  5. 5
    Add replicas
    A replica takes over if the main node dies, and loses far less data than a restart from disk.
  6. 6
    Plan the restart
    Loading many gigabytes from disk takes time. Test how long recovery takes, and what the app does meanwhile.
  7. 7
    Monitor memory
    Watch used memory, evictions, hit rate, replication lag and snapshot or log activity.
๐Ÿ’กDo the maths on loss
Writes per second times the seconds you might lose gives the number of writes at risk. If that number is not acceptable, shorten the gap, flush more often or add synchronous replication.
โš ๏ธA cache is not a database by default
Many products run as plain caches unless you switch persistence on. Do not store the only copy of important data in a cache that has no persistence and no replica.

08Key Terms to Know

TermMeaning in easy words
In-memory databaseA database that keeps its working data in RAM
RAMFast, temporary memory that is wiped when power is lost
PersistenceSaving data to disk so it survives a restart
SnapshotA full copy of the data written to disk at one moment
Append-only log (AOF / WAL)A file where every change is added to the end, to be replayed after a crash
fsync / flushForcing data from memory buffers onto the physical disk
ReplicationCopying changes to other machines
EvictionRemoving some data to free memory when RAM is full
TTLTime to live: the time after which a key is removed automatically
Cold startA restart where memory is empty and must be reloaded or refilled
Data loss windowThe amount of recent writes that could disappear in a crash

09Pros, Cons and Trade-offs

โœ… Pros
  • Extremely low latency
  • Very high throughput
  • Great for caches, sessions, counters and leaderboards
  • Simple data structures
  • Takes pressure off the main database
โš ๏ธ Cons
  • RAM is expensive
  • Capacity is limited by memory
  • Data can be lost without a durability plan
  • Restart and reload can be slow
  • Safer settings reduce write speed
  • Evictions can surprise you

Trade-offs

ChoiceWe gainWe lose
No persistenceTop speed, simplestAll data on restart
Snapshots onlyCheap and compactMinutes of data at risk
Log flushed every secondGood balanceUp to about a second of writes
Log flushed every writeNo acknowledged lossA big drop in write speed
Asynchronous replicaFast failover, small lossLag means a few recent writes can be lost
Synchronous replicaAlmost no lossEach write waits for the network

10Common Problems and Mistakes

Common mistakes

  1. No plan for restarts. A reboot empties the database and the main store is flooded with requests.
  2. Treating a cache as the source of truth. The only copy of important data lives in a store with no persistence.
  3. Running out of memory. Without an eviction rule or TTL, memory fills and writes fail or data is removed.
  4. Trusting "it saves to disk" blindly. If data is only flushed every few minutes, minutes of writes are at risk.
  5. Forgetting overhead. Real memory use is larger than the raw data because of keys, pointers and fragmentation.
  6. Snapshot pauses. A big snapshot can cost CPU, disk and extra memory at the wrong moment.
  7. Ignoring recovery time. Loading a huge dataset can take a long while.

Things to watch

๐Ÿ“ˆMemory growth
Watch used memory against the limit, and alert well before it is full.
๐ŸงนEvictions
A rising eviction count means the data no longer fits.
โณReplication lag
Large lag means a failover could lose more writes.
๐ŸฅถCold caches
After a restart the hit rate is zero, so the database behind it takes the load.

11Real-World Examples

๐ŸŸฅRedis
Often used as a cache, and also as a database with optional snapshots, a log and replication.
๐Ÿง Memcached
A simple in-memory cache for blobs, with no persistence.
โš™๏ธAerospike
A fast key-value database, often run with data in RAM and indexes tuned for speed.
๐Ÿ›๏ธSAP HANA
An in-memory database used for enterprise analytics and transactions.
๐ŸงฎSingleStore and VoltDB
Databases that keep hot data in memory for very fast transactions or queries.
๐ŸŽฎGaming and ad tech
Presence, scores and bidding data read and written thousands of times a second.
๐Ÿ“Note
Persistence and replication options differ by product and version. Always read the current documentation before you rely on durability.
Mini case: a leaderboard
๐ŸŽฎGame servers
โ†’โ†“score updates
โšกIn-memory DBsorted scores
โ†’โ†“log + replicate
๐Ÿ““Disk log
๐Ÿ–ฅ๏ธReplica
Scores live in memory for speed, with a log and a replica for safety.

12Related Topics to Read Next

Key-Value Databasesโ†’

Most in-memory databases are key-value stores.

Redis vs Memcachedโ†’

Two popular in-memory systems, with different durability.

Write-Ahead Log (WAL)โ†’

The log idea that makes a crash survivable.

Replicationโ†’

Copies on other machines reduce what a crash can lose.

Distributed Cache Architectureโ†’

How in-memory caches spread over many machines.

Cache Eviction Policiesโ†’

What to throw away when memory is full.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: data lives in RAM. Microsecond reads and writes.
  • โœ”Catch: RAM is costly, limited and wiped on restart.
  • โœ”Durability options: none, snapshots, log (per second or per write), replicas.
  • โœ”Rule: the safer the setting, the slower the writes.
  • โœ”Loss maths: writes per second ร— seconds at risk.
  • โœ”Cache vs database: a cache can be rebuilt. A primary store needs persistence and replicas.
  • โœ”Memory: add eviction rules and TTLs, and keep headroom.
  • โœ”One line: โ€œFast because it is in memory, safe only because you chose to save it.โ€
โ† Previous
Columnar Databases
Next โ†’
Indexing