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
  • Block Storage
  • Distributed File Systems
  • Object Storage
  • Erasure Coding
  • Storage Tiers (Hot, Warm, Cold)
  • RAID
  • Compression and Deduplication
  • File Storage (NFS)
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/Storage Systems

Compression and Deduplication

Store the same data in less space, by squeezing it or by keeping only one copy of repeats.

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

01Quick Summary

Compression and deduplication are two ways to store the same information in less space.

  • Compression rewrites data in a shorter form, by replacing repeated patterns with short references. Lossless compression gives back the exact original.
  • Deduplication finds identical chunks or files and keeps just one copy, with references from every place that used it.
  • Both save storage, network and I/O, and both cost CPU.

02Concept: What is it?

Real data is full of repeats. A log file repeats the same words on every line. A backup copied every night repeats most of yesterday's backup. Compression and deduplication are tools that notice those repeats and stop paying for them twice.

Compression works inside one piece of data. A simple idea is run-length encoding: write AAAAAAAAAA as "10 Γ— A". Real codecs are smarter. They find repeated patterns anywhere, point back to the earlier copy, and then use shorter codes for common symbols. Deduplication works across many pieces. It cuts files into chunks, computes a fingerprint (a hash) of each chunk, and stores a chunk only if that fingerprint is new.

Compression versus deduplication
Compression
πŸ“„AAAAAAAAAABBBB14 bytes
↓shorten repeats
πŸ—œοΈ10Γ—A 4Γ—B4 bytes
Deduplication
πŸ“„File 1A B C
πŸ“„File 2A B D
↓store each chunk once
A
B
C
D
Compression shrinks one item. Deduplication removes copies between items.
🧠Lossless and lossy
Lossless compression (gzip, zstd, LZ4, Snappy) restores every bit. Use it for text, databases, logs and backups. Lossy compression (JPEG, MP3, video codecs) throws away detail people will not notice. Use it for media you never need back exactly.

03Real-Life Example

🍡Packing a Suitcase and Sharing a Bookshelf
You are packing for a trip. Compression is vacuum-sealing your clothes: the same clothes take less room, and you get them back exactly as they were when you open the bag. Deduplication is a family of four sharing one copy of the guide book, instead of each buying their own. If everybody writes notes in the margin, you need your own copy again, because they are no longer identical.
Packing and sharing
Storage
Vacuum-sealing clothes
Lossless compression
Leaving behind what you will not miss
Lossy compression
Four people, one guide book
Deduplication
A sticker saying 'see the shared book'
A reference to a stored chunk
Vacuum-sealing something already sealed
Compressing already-compressed data
Losing the one shared book
Losing the only copy of a deduplicated chunk
Why order matters: compress, then encrypt
πŸ“„Datahas patterns
→↓compress
πŸ—œοΈSmaller
→↓encrypt
πŸ”’Random-lookingno patterns left

04Why Do We Need It?

πŸ’ΎLess storage
Logs, text and backups often shrink a lot, and so does repeated data, so you buy fewer disks.
🌐Less network
Smaller data uses less bandwidth between servers, data centres and users.
⚑Sometimes faster
Reading fewer bytes from disk or network can beat the cost of unpacking them.
πŸ’ΈLower bills
Cloud storage and transfer are charged by the gigabyte.
πŸ—„οΈLonger history
Deduplicated backups let you keep many daily versions for the price of a few.
πŸ“ŠFaster analytics
Columnar data compresses very well, so scans read much less.
Storage and bandwidth cost money. Do not pay twice for the same bytes, and do not pay full price for repeated patterns.

05Where Do We Use It?

🌐HTTP responses
Web servers compress text such as HTML, CSS, JavaScript and JSON before sending it.
πŸ—„οΈDatabases
Many databases compress pages or columns on disk, and columnar stores use it heavily.
πŸ“¨Message systems
Brokers and producers can compress batches of messages.
πŸ’ΎBackup tools
Backups chunk, deduplicate and compress to keep many versions cheaply.
☁️Object storage and file sync
File sync and storage services may deduplicate identical files or chunks.
πŸ–₯️Virtual machine images
Many VMs share most of their disk contents, which deduplication exploits.

06Types / Parts / How It Works

Compression families

KindExamplesWhat you getUse for
Lossless, fastLZ4, SnappyModerate shrinking, very high speed, low CPUHot data, databases, message batches
Lossless, stronggzip (deflate), zstd, bzip2, xzBetter shrinking, more CPU (zstd can be tuned between fast and strong)Logs, backups, files sent over the network, cold data
Lossy for mediaJPEG, MP3, video codecsLarge savings by dropping detail people barely noticeImages, audio and video
πŸ“Note
Which codec wins depends on the data and the settings. As a general rule, faster codecs shrink less and stronger ones cost more CPU, so measure on your own data.

A tiny compression example

Run-length encoding (a toy method)
input : AAAAAAAAAABBBBCC
runs  : 10 x A, 4 x B, 2 x C
output: 10A 4B 2C   (shorter, and fully reversible)

Real codecs such as gzip, zstd and LZ4 use a more general idea: when a pattern appeared earlier, replace it with a short pointer to the earlier copy ("go back 40 bytes and copy 12"). Some then also give common symbols shorter codes.

Deduplication: how chunks are cut

Fixed-size and content-defined chunks
Fixed-size chunks
ABC
DEF
GHI
↓insert N at the start
NAB
CDE
FGH
Every chunk changed, nothing matches
Content-defined chunks
ABC
DEF
GHI
↓insert N at the start
NABC
DEF
GHI
Only the first chunk changed
Insert one byte at the start of a file. Fixed chunks all shift. Content-defined cut points stay put.
LevelWhat is comparedGood and bad
File-levelWhole files by hashSimple and cheap. Misses files that differ by one byte.
Fixed-size blockEqual-sized blocksFast to compute. An insertion near the start shifts every block.
Content-defined chunksChunks cut where the content says so (rolling hash)Survives insertions well, but costs more CPU and has variable chunk sizes.
VisualizerSqueeze the text, then deduplicate the chunksIn demo 1 compare a repetitive log with random-looking text, and watch the compressed size. In demo 2 switch between fixed and content-defined chunks, then insert one unit at the start of Wednesday's file.
Pick a demo
Text to compress
Original (54 characters)
AAAAAAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCDDDDDDDD
Runs found: each run is stored as a count and a character
10Γ—A16Γ—B20Γ—C8Γ—D
Original
54 B
1 byte per character
Compressed
8 B
2 bytes per run
Size after
15%
of the original
Strong saving: 54 characters became 8 bytes. Long runs of the same character are exactly what run-length encoding is good at.

Teaching toy: run-length encoding only spots the same character repeated. Real codecs (gzip, zstd, LZ4, Snappy) find repeated patterns anywhere in the data and then code the result compactly, so they do far better on text. Already-compressed or encrypted data looks random and barely shrinks at all, as the "Random-looking" example shows.

07How to Use It / Steps / Implementation

Using compression and deduplication well

  1. 1
    Check what the data is
    Text, JSON, logs and columns shrink well. Images, video and encrypted data are already dense and barely shrink.
  2. 2
    Pick the codec for the job
    Use a fast codec (LZ4, Snappy, low-level zstd) on hot paths. Use a stronger setting for cold data and backups that are written once.
  3. 3
    Compress before you encrypt
    Encrypted data looks random and cannot be compressed. Compress first, then encrypt.
  4. 4
    Compress at the right layer
    Compress where it helps most: on the wire, in the database, or in the object. Avoid compressing the same data twice.
  5. 5
    Measure the ratio and the CPU
    Test on real samples. Compare the saved bytes with the CPU time and the extra latency.
  6. 6
    Deduplicate where repeats are common
    Backups, VM images and file sync have lots of repeats. A busy database table usually does not.
  7. 7
    Protect the single copy
    With deduplication, one damaged chunk breaks every file that uses it. Keep replicas and verify checksums.
πŸ’‘Compress batches, not single tiny messages
A codec needs enough data to find patterns. Compressing a 50-byte message may even make it larger. Group many messages into a batch and compress the batch.
⚠️Careful with secrets and compression together
If an attacker can influence part of the data and can see the compressed size, size changes can leak secret information. Web security guides cover this for compressed responses that mix secrets with user-controlled text.

08Key Terms to Know

TermMeaning in easy words
CompressionStoring data in fewer bytes by removing repetition
LosslessCompression that restores the exact original data
LossyCompression that drops some detail for a much smaller size
Compression ratioHow much smaller the data became, e.g. compressed size divided by original size
Run-length encodingReplacing a run of the same symbol with a count and the symbol
Dictionary codingReplacing repeated patterns with references to earlier copies
DeduplicationKeeping one copy of identical data and referencing it from every use
ChunkA piece of a file used as the unit of deduplication
FingerprintA hash of a chunk used to detect whether it has been seen before
Content-defined chunkingCutting chunks at points decided by the data, not by position
Reference countingCounting how many files use a chunk, so it is removed only when none do

09Pros, Cons and Trade-offs

βœ… Pros
  • Saves storage and bandwidth
  • Can speed up reads by moving fewer bytes
  • Cheap backups with many versions (deduplication)
  • Lossless compression is safe for any data
  • Supported almost everywhere by default
⚠️ Cons
  • Costs CPU time to pack and unpack
  • Incompressible data gains nothing
  • Deduplication needs a fingerprint index and extra memory
  • One damaged shared chunk affects many files
  • Adds complexity to updates, deletes and garbage collection

Trade-offs

ChoiceWe gainWe lose
Stronger compressionSmaller dataMore CPU and slower writes or reads
Faster compressionLow latency and CPULarger data
Lossy compressionVery small media filesExact originals can never be restored
DeduplicationBig savings when data repeatsIndex memory, CPU and a shared-chunk risk
Small chunksMore matches foundA bigger index and more references
Large chunksA small index and fast processingFewer matches, as small changes break whole chunks

10Common Problems and Mistakes

Common mistakes

  1. Compressing already-compressed data. JPEG, MP4 and archives gain nothing and waste CPU.
  2. Encrypting before compressing. Encrypted bytes look random, so nothing can be shrunk.
  3. Choosing the strongest setting everywhere. The CPU cost can slow a busy service more than the saved bytes help.
  4. Deduplicating with no backup of the chunks. One bad disk sector can damage many files.
  5. Forgetting garbage collection. Chunks that nobody references must be found and removed, safely.
  6. Compressing tiny messages one by one. The overhead can make them bigger.
  7. Mixing secrets with attacker-controlled text in compressed output. The size can leak information.

Things to watch

πŸ”₯CPU spikes
Heavy compression on a hot path raises latency. Watch CPU and p99 latency.
πŸ’£Decompression bombs
A tiny file can expand to a huge one. Limit the output size when you unpack untrusted data.
🧩Fragmentation
Deduplicated files are made of scattered chunks, so reading them can be slower.
πŸ•΅οΈCross-user dedup
Sharing chunks between different users can reveal that someone else already has a file. Systems often avoid it or add protections.

11Real-World Examples

🌐Web servers
HTTP compression with gzip or Brotli shrinks text responses on the wire.
πŸ—„οΈColumn stores
Columnar databases compress each column strongly, because values in a column look alike.
πŸ“¨Kafka-style logs
Producers compress batches of messages, which cuts network and disk use.
πŸ’ΎBackup software
Many backup tools split data into chunks, deduplicate them and compress what is left.
🧊Cold storage
Archives are often compressed with a strong codec, as they are written once and read rarely.
πŸ–₯️Storage arrays
Some arrays and file systems offer inline compression and deduplication as options.
πŸ“Note
Savings depend entirely on your data. Vendors quote ratios for typical data, but your own measurement is the only number that counts.
Mini case: a week of nightly backups
πŸ’Ύ7 backups7 Γ— 100 GB = 700 GB
→↓chunk + dedup
🧩Unique chunksabout 100 GB + changes
→↓compress
πŸ—œοΈStoredmuch smaller
Without dedupillustrative
With dedupillustrative
Raw Stored
Illustrative: most of the data is the same every night.

12Related Topics to Read Next

Columnar Databases→

Values in a column look alike, so they compress extremely well.

Checksums→

Fingerprints for chunks, and a way to catch damage to a shared copy.

Object Storage→

A common place where compressed and deduplicated data ends up.

Data Formats→

Formats like Parquet and JSON compress very differently.

Storage Tiers (Hot, Warm, Cold)β†’

Cold tiers pair well with strong compression.

Merkle Trees→

Hash trees that compare chunks of data quickly.

Backups, RPO, RTO and Disaster Recovery→

The main place deduplication pays off.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Compression: shorter form of one item. Lossless = exact, lossy = detail dropped.
  • βœ”Dedup: chunk, hash, store each unique chunk once, keep references.
  • βœ”Codecs: LZ4 and Snappy fast, zstd and gzip stronger. Measure on your data.
  • βœ”Order: compress first, then encrypt.
  • βœ”Chunking: content-defined survives insertions, fixed-size does not.
  • βœ”Costs: CPU, index memory, and a shared-chunk risk. Keep replicas and checksums.
  • βœ”Skip it for: JPEG, video, encrypted data and tiny messages.
  • βœ”One line: β€œNever pay twice for the same bytes, and never pay full price for repeats.”
← Previous
RAID
Next β†’
File Storage (NFS)