Blob and Object Storage
Photos, videos, backups, logs, ML datasets: most of the bytes in a large system are blobs (binary large objects). They don't belong in a relational database, which is optimised for small rows and transactions. They go into object storage: Amazon S3, Google Cloud Storage, Azure Blob Storage, or self-hosted MinIO and Ceph.
The object storage model
| Concept | Meaning |
|---|---|
| Bucket | A named container, with its own access policy and region |
| Key | The object's name, e.g. users/42/avatar.jpg (the "folders" are just a prefix) |
| Object | The bytes plus metadata (content type, size, ETag checksum, custom headers) |
| Operations | PUT, GET (also byte ranges), DELETE, LIST by prefix, multipart upload |
Objects are immutable: you replace an object as a whole, you don't edit bytes in the middle. In exchange you get practically unlimited capacity, very high durability (S3 is designed for 99.999999999%, "eleven nines"), low cost per GB and HTTP access from anywhere.
| Block storage (EBS, disks) | File storage (NFS, EFS) | Object storage (S3) | |
|---|---|---|---|
| Interface | Raw blocks for one machine | Shared POSIX file system | HTTP API |
| Edit in place | Yes | Yes | No, replace whole object |
| Scale | One volume, TBs | Shared, TBs-PBs | Unlimited, exabytes |
| Latency | Sub-millisecond | Milliseconds | Tens of milliseconds |
| Typical use | Database disks | Shared home directories, legacy apps | Media, backups, data lakes, static sites |
Metadata in the database, bytes in the object store
The standard pattern: the database row stores who owns what (owner, key, size, checksum, status); the object store holds the bytes. Uploads go directly from the client to the object store with a pre-signed URL, so the app servers never touch the large payload.
1. client -> app: "I want to upload avatar.jpg (2 MB)"
2. app -> db: INSERT photo (id=901, owner=42, key='u/42/901.jpg', status='pending')
3. app -> client: pre-signed PUT URL, valid 10 minutes
4. client -> S3: PUT bytes using the URL (app servers not involved)
5. S3 -> app: "object created" event -> status='ready', start thumbnailingA pre-signed URL is just the request details plus an expiry, signed with a secret key; the store verifies the signature. Here's the idea with an HMAC:
import hashlib
import hmac
SECRET = b"server-side-secret"
def presign(method, bucket, key, expires_at):
message = f"{method}\n{bucket}\n{key}\n{expires_at}".encode()
sig = hmac.new(SECRET, message, hashlib.sha256).hexdigest()[:16]
return f"https://{bucket}.store.example/{key}?expires={expires_at}&sig={sig}"
def verify(method, url, now):
host, rest = url.split("://")[1].split("/", 1)
key, query = rest.split("?")
params = dict(p.split("=") for p in query.split("&"))
bucket = host.split(".")[0]
if now > int(params["expires"]):
return "403 expired"
expected = presign(method, bucket, key, int(params["expires"])).split("sig=")[1]
return "200 ok" if hmac.compare_digest(expected, params["sig"]) else "403 bad signature"
url = presign("PUT", "photos", "u/42/901.jpg", expires_at=1_000_600)
print(url)
print("upload at t=1,000,100:", verify("PUT", url, now=1_000_100))
print("upload at t=1,000,700:", verify("PUT", url, now=1_000_700))
print("tampered key: ", verify("PUT", url.replace("901", "902"), now=1_000_100))https://photos.store.example/u/42/901.jpg?expires=1000600&sig=54c3d56bdb14cb76
upload at t=1,000,100: 200 ok
upload at t=1,000,700: 403 expired
tampered key: 403 bad signature
Multipart uploads
Large files are uploaded in parts (S3: 5 MB to 5 GB each, up to 10,000 parts), in parallel, and retried individually. The final "complete" call stitches them together.
import math
def plan_parts(size_bytes, part_size=8 * 1024 * 1024):
count = math.ceil(size_bytes / part_size)
return [(i + 1, i * part_size, min(part_size, size_bytes - i * part_size)) for i in range(count)]
video = 50 * 1024 * 1024 + 123 # a 50 MiB file plus a few bytes
parts = plan_parts(video)
for number, offset, length in parts:
print(f"part {number}: offset {offset:>10,} length {length:>10,}")
print("parts:", len(parts), "total:", sum(p[2] for p in parts) == video)
# A failed part is retried alone instead of re-sending 50 MiB
failed = {3}
resent = sum(length for number, _, length in parts if number in failed)
print(f"retry after a failure re-sends {resent / video:.0%} of the file")part 1: offset 0 length 8,388,608
part 2: offset 8,388,608 length 8,388,608
part 3: offset 16,777,216 length 8,388,608
part 4: offset 25,165,824 length 8,388,608
part 5: offset 33,554,432 length 8,388,608
part 6: offset 41,943,040 length 8,388,608
part 7: offset 50,331,648 length 2,097,275
parts: 7 total: True
retry after a failure re-sends 16% of the file
How durability is achieved
Object stores keep data safe by spreading redundancy across disks, racks and availability zones. Two techniques:
- Replication: 3 full copies. Simple, fast to read, but 200% storage overhead.
- Erasure coding: split data into
kdata chunks plusmparity chunks; anykof thek + mchunks rebuild the object. Much cheaper for the same durability.
from math import comb
def survival(total_chunks, needed, p_chunk_loss):
# probability that at least `needed` chunks survive (independent losses)
return sum(comb(total_chunks, lost) * p_chunk_loss**lost * (1 - p_chunk_loss)**(total_chunks - lost)
for lost in range(total_chunks - needed + 1))
p = 0.01 # chance a chunk is lost before repair finishes
schemes = {"3x replication": (3, 1), "erasure 6+3": (9, 6), "erasure 10+4": (14, 10)}
for name, (total, needed) in schemes.items():
overhead = total / needed - 1
loss = 1 - survival(total, needed, p)
print(f"{name:<15} storage overhead {overhead:5.0%} P(object lost) {loss:.1e}")3x replication storage overhead 200% P(object lost) 1.0e-06
erasure 6+3 storage overhead 50% P(object lost) 1.2e-06
erasure 10+4 storage overhead 40% P(object lost) 1.9e-07
Erasure coding 10+4 survives more simultaneous losses than triple replication with a fifth of the overhead. The cost: reading or repairing a chunk needs data from several other machines.
Design tips
- Name keys for access patterns, not for humans:
u/42/901.jpgfor per-user listing, or prefix with a hash to spread very hot prefixes. - Serve through a CDN; never stream large files through app servers.
- Use lifecycle rules: move objects to cheaper "infrequent access" or archive tiers after N days and delete temporary uploads automatically.
- Version buckets or use object lock for backups, so a bug or ransomware can't overwrite them.
- Store a checksum (ETag / SHA-256) in your metadata and verify it after upload.
Test yourself
Where should a photo-sharing app store photo bytes and photo metadata?
- Both in the relational database
- Bytes in object storage, metadata (owner, key, size) in a database
- Both in object storage only
- Bytes in Redis
What is the benefit of a pre-signed upload URL?
- It compresses the file
- Clients upload directly to the object store with temporary, limited permission, bypassing app servers
- It makes the file public forever
- It removes the need for authentication
Why is erasure coding cheaper than 3x replication?
- It stores fewer bytes of redundancy for similar or better durability
- It uses faster disks
- It never needs repairs
- It stores data only once