Courses / System Design Interview / Chapter 19
Module 4 · Building Blocks III: Limits, Storage and Search · Chapter 19 of 49
Blob Stores
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Building Blocks: The Parts Every Design Reuses and Design a Distributed Key-Value Store. Next up: Distributed Search.
Part 1 · What a blob store is for
Large values that are written once
A phone photo, a lecture video and a database backup are all large files that an app stores once and reads many times. A blob store, also called an object store, is the service built for exactly that.
A blob (binary large object) is a sequence of bytes with a name. The store does not look inside it. You write the whole blob under a name, called the key, and later read it back by that key. You do not change a few bytes in the middle: to change a blob, you write a new version under the same key, which replaces the old one.
That small set of rules is what lets blob stores grow so large. There is no schema to enforce, no join between blobs, and no transaction across two keys. The store only has to keep every byte safe and hand it back on request.
It helps to place a blob store beside the two other kinds of storage a computer room offers.
| Kind | What you get | Access | Typical use |
|---|---|---|---|
| Block storage | A raw disk of fixed-size blocks | One machine at a time, very low delay | A database's data files |
| File storage | Folders and files, shared | File system calls, in-place edits | Home directories, shared documents |
| Blob (object) storage | A flat set of named blobs | HTTP calls, whole-object writes | Photos, video, backups, logs, static files |
Why not a database column
A database can hold bytes in a column, and for small values that is fine. For a photo of 3 MB or a video of 300 MB it goes wrong in several ways.
- The database is the expensive part. Disks, memory and replicas for a database cost far more per gigabyte than a store built only to hold bytes.
- Large rows crowd out useful data. A database keeps recently used pages in memory. Big values push the small, hot rows out of that memory.
- Backups and copies grow. Every replica and every backup now carries the media too, and replication traffic grows with it.
- Reads cannot be split cheaply. A browser fetching a video wants a range of bytes and a CDN wants to cache it, and both are simpler with a plain URL than with a database query.
The usual design keeps the row small and puts the bytes elsewhere. The database stores the metadata that you want to query, such as who uploaded the photo, when, and the key of its blob. The blob store stores the bytes. A page that shows the photo asks the database for the row and then fetches the blob by key, often through a CDN.
Facebook's engineers described one such system in the OSDI 2010 paper "Finding a Needle in Haystack: Facebook's Photo Storage". The point to take from the title alone is that serving a very large number of photos was important enough to need a purpose-built store.
What the store must do
Before designing the inside, write down what outside callers need. The functional list is short.
- Put a blob under a key, and replace it if the key exists.
- Get a blob by key, or only a range of its bytes.
- Delete a key.
- List the keys in a bucket that start with a given prefix.
- Upload large blobs reliably, in parts, so that one network failure does not restart the whole transfer.
The non-functional list decides the design. Durability is the chance that a stored blob is still there and unchanged later. It is the most important property, because losing a customer's data cannot be repaired. Availability is the share of requests that succeed. Throughput is how many bytes per second the system can move. Cost per gigabyte matters more here than in almost any other building block, because blob stores hold most of the bytes of a company.
Durability and cost pull against each other. Keeping three full copies is simple and sturdy, and it triples the bill. Later lessons show how placement keeps copies apart, and how erasure coding cuts the cost while keeping durability.
| Term | Meaning |
|---|---|
| Blob or object | A named sequence of bytes that is written and read as a whole |
| Key | The name of a blob, unique inside its bucket |
| Bucket | A named container of keys, used to group and to set rules |
| Durability | The chance that stored data survives, unchanged |
| Metadata | Small facts about a blob: size, type, time, location |
Part 2 · Buckets, keys and the API
Buckets, keys and metadata
A bucket is a named container, and a key is a string that names one blob inside it. The pair of bucket and key is the blob's address. Most object stores give each blob a URL built from the two, so a browser or a program can fetch it with one HTTP request.
The namespace inside a bucket is flat. A key such as 2026/day1.txt contains a slash, but the store sees one string, not a folder and a file. Folders are a convention built on listing by prefix: asking for the keys that start with 2026/ returns everything that looks like it is inside that folder. The consequence is that there is no cheap rename. Moving a blob to a new key means copying it and deleting the old one.
Each blob also carries metadata, small facts that travel with it. Some are set by the system: the size, the time of the last change, and an ETag, a short identifier that changes when the content changes and lets a client tell whether its copy is current. Others are set by the caller: the content type, such as text/plain, and custom labels. The ETag in the Amazon S3 documentation is described as not necessarily an MD5 hash of the data, so treat it as an opaque version marker. The server in this lesson uses the first 16 characters of a SHA-256 hash.
The API is a handful of HTTP calls, because HTTP already has the right verbs.
| Call | Meaning | Notes |
|---|---|---|
| PUT /bucket/key | Store or replace the blob | The body is the whole object |
| GET /bucket/key | Read the blob | A Range header can ask for part of it (the server below does not implement ranges) |
| HEAD /bucket/key | Read only the metadata |
A small blob server
The server below keeps blobs in a Python dictionary, which is enough to show the interface. It uses the standard http.server module and listens only on 127.0.0.1, on port 55483. The first part holds the helpers and PUT. The second part adds listing, GET, HEAD and DELETE.
import hashlib from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlsplit, parse_qs store = {} # (bucket, key) -> (bytes, content type) class Blob(BaseHTTPRequestHandler): def reply(self, code, body=b"", headers=()): self.send_response(code) for k, v in headers: self.send_header(k, v) self.send_header("Content-Length", str(len(body))) self.end_headers() if self.command != "HEAD": self.wfile.write(body) def where(self): u = urlsplit(self.path) bucket, _, key = u.path.lstrip("/").partition("/") return bucket, key, parse_qs(u.query) def do_PUT(self): bucket, key, _ = self.where() data = self.rfile.read(int(self.headers["Content-Length"])) ctype = self.headers.get("Content-Type", "bytes") store[(bucket, key)] = (data, ctype) tag = hashlib.sha256(data).hexdigest()[:16] self.reply(200, headers=[("ETag", f'"{tag}"')])
l2_server.py, part 1: helpers and PUT
def do_GET(self): bucket, key, q = self.where() if not key: # list keys with a prefix pre = q.get("prefix", [""])[0] names = sorted(k for b, k in store if b == bucket and k.startswith(pre)) return self.reply(200, "\n".join(names).encode() + b"\n") if (bucket, key) not in store: return self.reply(404, b"no such key\n") data, ctype = store[(bucket, key)] self.reply(200, data, [("Content-Type", ctype)]) do_HEAD = do_GET def do_DELETE(self): bucket, key, _ = self.where() store.pop((bucket, key), None) self.reply(204) def log_message(self, *a): pass ThreadingHTTPServer(("127.0.0.1", 55483), Blob).serve_forever()
l2_server.py, part 2: GET, list, HEAD and DELETE
A request to the bucket without a key, such as /notes?prefix=2026/, is a listing. A request with a key fetches or changes one blob. A missing key gives 404. HEAD is handled by the same code as GET, and reply skips the body for it.
Using it, and the quiz
The run below uses curl 8.21.0. It stores a blob with a content type, reads it back, lists by prefix, deletes it, and then asks for it again. Two earlier PUTs of the same kind stored notes/2026/day2.txt and notes/readme.txt; they are left out of the transcript. The Date and Server headers were removed from the output.
$ B=http://127.0.0.1:55483 $ curl -i -X PUT -H "Content-Type: text/plain" \ --data-binary "hello, blob" $B/notes/2026/day1.txt HTTP/1.0 200 OK ETag: "d867e6d01ad026f7" Content-Length: 0 $ curl -s $B/notes/2026/day1.txt hello, blob $ curl -s "$B/notes?prefix=2026/" 2026/day1.txt 2026/day2.txt $ curl -s -X DELETE -w "%{http_code}\n" $B/notes/2026/day1.txt 204 $ curl -s -w "%{http_code}\n" $B/notes/2026/day1.txt no such key 404
The PUT answered 200 with an ETag, and the content came back byte for byte. The listing with the prefix 2026/ returned the two keys inside that folder and left out readme.txt. After the DELETE, the same GET returned 404.
Because this server is one process with one dictionary, a read right after a write always sees the write. A distributed store has to work for that. Amazon S3 announced on 1 December 2020 that it provides strong read-after-write consistency for all applications, which means a read or a listing right after a successful write or overwrite sees the new data. Not every store makes that promise, so check what the one you use guarantees.
A client uploads photos/2026/a.jpg and photos/2026/b.jpg. How does it list "the folder"?
- It lists the keys with the prefix
photos/2026/. - The slash is only part of the key name, and the store has no real folders.
Why can a client safely retry a DELETE after a timeout?
- DELETE is idempotent: the state after two deletes equals the state after one.
What does a client learn from HEAD that it would not want to pay for with GET?
- The size, type and ETag of the blob, without transferring its bytes.
Part 3 · Chunking and multipart upload
Why large uploads go in parts
Sending a 4 GB video in one request has two problems. If the connection drops at 3.9 GB, the whole transfer starts again. And a single connection may use only a part of the available bandwidth.
Multipart upload fixes both by cutting the file into parts and sending each as its own request. The Amazon S3 documentation lists the benefits: parts can be uploaded in parallel for better throughput, a failed part can be sent again without touching the others, an upload can be paused and resumed, and an upload can start before the final size is known.
The protocol has three steps. First, the client initiates the upload, and the store returns an upload id. Second, the client sends each part with the upload id and a part number, which fixes the part's position in the final object. Parts may arrive in any order. Third, the client completes the upload by sending the list of part numbers with a checksum for each. The store checks the list, joins the parts in number order, and only then makes the object visible. Before that moment, no reader can see a half-built object.
A checksum is a short fingerprint computed from the bytes, here SHA-256. If a part is damaged in transit, its checksum no longer matches and the store refuses it. The client resends just that part.
The limits in the S3 documentation show how the numbers fit together. A part is 5 MiB to 5 GiB, except that the last part may be smaller. An upload has at most 10,000 parts, numbered 1 to 10,000. The documentation also says to consider multipart upload once an object reaches 100 MB.
A multipart store in code
The class below models the three steps. put_part refuses a part whose checksum does not match what the client claims. complete takes the manifest, which is the list of part numbers and checksums, and joins the stored parts in order.
import hashlib def sha(data): return hashlib.sha256(data).hexdigest() class Store: def __init__(self): self.uploads, self.objects = {}, {} def initiate(self, key): uid = f"upload-{len(self.uploads) + 1}" self.uploads[uid] = (key, {}) return uid def put_part(self, uid, n, data, claimed): if sha(data) != claimed: raise ValueError(f"part {n}: checksum mismatch, not stored") self.uploads[uid][1][n] = (data, claimed) def complete(self, uid, manifest): # manifest: [(n, sha)] key, parts = self.uploads[uid] body = b"" for n, claimed in sorted(manifest): data, stored = parts[n] assert stored == claimed, f"part {n} differs from manifest" body += data del self.uploads[uid] self.objects[key] = body return sha(body)
multipart.py: initiate, put_part and complete
The run cuts a pseudo-random file of 10 lakh bytes into parts of 256 KiB, which gives four parts. It uploads them out of order, as 3, 1, 4, 2. On its first attempt, part 4 is damaged in transit by changing its first byte. It was run with Python 3.12.10.
import math, random, sys from multipart import Store, sha print(sys.version.split()[0]) random.seed(5) data = random.randbytes(1_000_000) # the "file" PART = 256 * 1024 parts = [data[i:i + PART] for i in range(0, len(data), PART)] manifest = [(n, sha(p)) for n, p in enumerate(parts, start=1)] for n, p in enumerate(parts, start=1): print(f"part {n}: {len(p):7} bytes sha256 {sha(p)[:12]}")
l3_run.py, part 1: cut the file and list the parts
store = Store() uid = store.initiate("videos/lecture.mp4") damaged = {4} # part 4 is corrupted on its first try for n in (3, 1, 4, 2): # parts arrive out of order p = parts[n - 1] wire = b"x" + p[1:] if n in damaged else p damaged.discard(n) try: store.put_part(uid, n, wire, sha(p)) print(f"uploaded part {n}") except ValueError as e: print("rejected:", e) store.put_part(uid, n, p, sha(p)) # resend only this part print(f"resent part {n}") store.complete(uid, manifest) same = store.objects["videos/lecture.mp4"] == data print("object equals the original:", same) GIB, TIB = 2**30, 2**40 print(f"5 GiB x 10,000 parts = {5 * GIB * 10_000 / TIB:.2f} TiB") n = math.ceil(100 * GIB / (100 * 2**20)) print("100 GiB in 100 MiB parts:", n, "parts")
l3_run.py, part 2: upload out of order, resend one part
What the run shows, and the quiz
3.12.10 part 1: 262144 bytes sha256 0498e42035e6 part 2: 262144 bytes sha256 5f15e043fc67 part 3: 262144 bytes sha256 a462c87386fc part 4: 213568 bytes sha256 e1097d55776f uploaded part 3 uploaded part 1 rejected: part 4: checksum mismatch, not stored resent part 4 uploaded part 2 object equals the original: True 5 GiB x 10,000 parts = 48.83 TiB 100 GiB in 100 MiB parts: 1024 parts
The four parts are 2,62,144 bytes each, except the last, which holds the 2,13,568 bytes that remain. That is the same exception S3 makes for the final part. Parts 3 and 1 were accepted. Part 4 was rejected with a checksum mismatch, so the client sent it again, and nothing else had to be repeated. After part 2 arrived, complete produced an object equal to the original.
The last two lines are arithmetic on the S3 limits. The largest part, 5 GiB, times the largest part count, 10,000, is 48.83 TiB, which agrees with the maximum object size of 48.8 TiB that the documentation gives. And a 100 GiB file cut into 100 MiB parts needs 1,024 parts.
Two operational points matter. First, an unfinished multipart upload still occupies storage. The S3 documentation says you are billed for the stored parts until you complete or stop the upload, and it recommends a lifecycle rule that deletes incomplete uploads after some number of days. Any store of this kind needs that cleanup. Second, keep a record of every part on the client. The documentation says the completion request must carry each part number with the ETag the store returned for it, and tells clients to keep their own list of these and not to build the request from a listing of the parts.
A file of 10 lakh bytes is cut into 256 KiB parts. How many parts are there, and why is the last one smaller?
- Four parts. Three hold 2,62,144 bytes and the last holds the remaining 2,13,568.
- A file rarely divides into equal parts, so the last part takes what is left.
Part 4 arrives damaged. What must the client resend?
- Only part 4. The checksum check rejected that part alone, and the other parts are stored.
- That is one benefit of multipart upload.
Part 4 · Metadata service, data nodes and placement
Two kinds of servers
Inside a large blob store, the work splits into two layers with very different needs.
The metadata service is the small, busy part. It knows which blobs exist, which chunks make up each blob, and which data nodes hold each chunk. It must answer quickly, and it must be correct, so it is usually backed by a replicated database. The data nodes are the large, simple part. Each is a server with many disks that stores chunks by id and returns them. They know nothing about keys or buckets.
A front end receives the HTTP request, asks the metadata service where to put or find the chunks, and moves the bytes to or from the data nodes. When the S3 post-mortem of 2017, which a later chapter reads, lists the parts of S3, it names an index subsystem that holds the metadata and location information of objects and a placement subsystem that allocates storage for new objects. The same split appears there.
A chunk is a piece of a blob, typically some megabytes. A blob smaller than a chunk is one chunk. Chunking keeps the unit of storage and repair small and fixed, however large the blob is, so a 4 GB video spreads over many nodes and a failed disk loses only a few chunks to rebuild.
Watch for the metadata service choosing the nodes before any bytes move
Read it as steps
Choosing nodes
For each chunk the metadata service must choose a few distinct data nodes, and the choice must spread chunks evenly. One simple method is rendezvous hashing, also called highest-random-weight hashing. For a chunk, compute a score for every node by hashing the node's name together with the chunk id. Sort the nodes by score. The first three are the chunk's nodes.
The method needs no table of assignments to decide, because any server that knows the node list reaches the same answer. It gives distinct nodes by construction, since each node appears once in the ranking. And when a node fails, the chunks it held take their next-best node from the same ranking, while chunks that did not use that node stay where they are.
Real placement also looks at failure domains. Three copies on three servers in one rack are lost together if the rack loses power, so production systems pick nodes in different racks or zones. The code here uses only node names, to keep the idea visible.
import hashlib def score(node, chunk): h = hashlib.sha256(f"{node}|{chunk}".encode()).digest() return int.from_bytes(h[:8], "big") class Metadata: """Which chunks make an object, and which nodes hold each chunk.""" def __init__(self, nodes, copies=3): self.live, self.copies = set(nodes), copies self.objects, self.holders = {}, {} def ranked(self, chunk): # best node first return sorted(self.live, key=lambda n: -score(n, chunk))
placement.py: the metadata service, part 1
def put(self, key, n_chunks): ids = [f"{key}#{i}" for i in range(n_chunks)] self.objects[key] = ids for c in ids: self.holders[c] = self.ranked(c)[:self.copies] def fail(self, node): self.live.discard(node) moved = 0 for c, hs in self.holders.items(): if node in hs: hs.remove(node) new = [n for n in self.ranked(c) if n not in hs][0] hs.append(new) moved += 1 return moved
placement.py: the metadata service, part 2
Run: place, fail, repair
The run stores 200 objects of five chunks each, which is 1,000 chunks, on five nodes with three copies of each. It then fails node n3 and repairs. fail gives every chunk that held a copy on n3 a new copy on its next-best live node.
from collections import Counter from placement import Metadata nodes = ["n1", "n2", "n3", "n4", "n5"] m = Metadata(nodes, copies=3) for i in range(200): # 200 objects of 5 chunks each m.put(f"obj{i}", 5) def load(): c = Counter(n for hs in m.holders.values() for n in hs) return {n: c[n] for n in sorted(m.live)} print("chunks:", len(m.holders), " copies each:", m.copies) print("per node:", load()) print("distinct nodes for every chunk:", all(len(set(hs)) == 3 for hs in m.holders.values())) print("n3 fails") print("chunks re-replicated:", m.fail("n3")) print("per node:", load()) print("distinct live nodes for every chunk:", all(len(set(hs)) == 3 and "n3" not in hs for hs in m.holders.values()))
l4_run.py: 1,000 chunks, 3 copies, then n3 fails
chunks: 1000 copies each: 3 per node: {'n1': 629, 'n2': 623, 'n3': 557, 'n4': 592, 'n5': 599} distinct nodes for every chunk: True n3 fails chunks re-replicated: 557 per node: {'n1': 778, 'n2': 760, 'n4': 727, 'n5': 735} distinct live nodes for every chunk: True
Three copies of 1,000 chunks make 3,000 copies, about 600 on each of five nodes; the run shows between 557 and 629. After n3 fails, 557 chunks had lost a copy, exactly the number n3 held, and each got a new one. The four survivors now carry about 750 copies each, and every chunk again has three copies on three distinct live nodes. No chunk that did not use n3 was touched.
In a real system the repair is real data movement, so it takes time and network. A store must start the repair quickly, because a second failure during the repair of the first is the way a chunk with three copies gets lost, and it must limit the repair traffic so that user requests still get through.
Why does the metadata service choose the nodes before the front end sends any bytes?
- The bytes have to go to specific nodes, and the metadata service is the only place that knows the layout and records it.
- The choice must also be written down, or the blob could not be found later.
Part 5 · Replication and erasure coding
Copies, and what they cost
The simplest way to survive failures is replication: keep several full copies on different nodes. With three copies, a blob survives the loss of any two of the nodes that hold it. Reads are simple, since any copy can serve them, and repair is a plain copy.
The price is the storage overhead, the raw disk used for each byte of data. Three copies cost 3.0x. For data that is read often, that is the right trade, because reads can go to any copy. For a very large amount of data that is rarely read, such as old photos and videos, paying 3x for disks that mostly sit idle is wasteful.
Facebook's f4 paper, from OSDI 2014, is about warm blobs, the ones read less often than new content. Its abstract reports that the design reduces the effective replication factor from 3.6 to either 2.8 or 2.1, over more than 65 PB of logical data. The effective replication factor is raw bytes stored divided by logical bytes. The abstract does not describe the mechanism, so this lesson does not attribute any one technique to that system. It shows what the numbers are worth: moving from 3.6 to 2.1 stores the same data on about 42 percent less disk.
The standard technique for lowering overhead while keeping durability is erasure coding.
Erasure coding
An erasure code splits data into k data pieces and computes m extra parity pieces, so that any k of the k + m pieces are enough to rebuild the data. The code is written k + m. A 10+4 code makes 14 pieces from 10 and survives the loss of any four of them.
The storage overhead is (k + m) / k. For 10+4 it is 14 / 10 = 1.4x. Compare that with 3 copies at 3.0x, which survive two losses: the code survives more losses with less than half the disk. The codes used in practice for this, such as Reed-Solomon codes, do the arithmetic over a finite field, which is beyond this lesson. The idea can be seen with the simplest case: one parity piece made with XOR.
XOR (exclusive or) combines two bytes so that applying the same value twice undoes it: (a xor b) xor b gives a. So if the parity piece is the XOR of all data pieces, any single missing piece equals the XOR of everything that is left. This is a k+1 code. It survives one loss, like the parity of RAID 5.
import random from functools import reduce def xor(a, b): return bytes(x ^ y for x, y in zip(a, b)) random.seed(11) data = random.randbytes(1000) k = 4 # four data shards of 250 bytes shards = [data[i * 250:(i + 1) * 250] for i in range(k)] parity = reduce(xor, shards) # one parity shard lost = 2 # shard 2 is on a failed node rest = [s for i, s in enumerate(shards) if i != lost] rebuilt = reduce(xor, rest + [parity]) ok = rebuilt == shards[lost] print("one shard lost, rebuilt equals the original:", ok) lost2 = 0 # now shard 0 is gone as well rest2 = [s for i, s in enumerate(shards) if i not in (lost, lost2)] guess = reduce(xor, rest2 + [parity]) print("two lost, guess equals shard 2:", guess == shards[2], "| equals shard 0:", guess == shards[0]) both = xor(shards[0], shards[2]) print("guess is shard 0 xor shard 2:", guess == both)
l5_run.py: four data shards and one XOR parity shard
one shard lost, rebuilt equals the original: True two lost, guess equals shard 2: False | equals shard 0: False guess is shard 0 xor shard 2: True
Reading the run, and the cost of repair
With one shard lost, the XOR of the three data shards and the parity gave the missing shard back exactly. With two shards lost, the same calculation gave a value that equals neither of them. It equals shard 0 xor shard 2, which is the one equation the parity can still supply. One parity piece cannot solve for two unknowns, and a 10+4 code carries four equations for up to four unknowns.
The next run prints the overhead of four schemes. A 6+3 code is added as a middle case. The numbers come from the formula, not from an encoder.
PB = 1.0 # logical data, in petabytes schemes = [("3 copies", 1, 2), ("XOR 4+1", 4, 1), ("6+3 code", 6, 3), ("10+4 code", 10, 4)] head = ("scheme", "pieces", "lost ok", "overhead", "1 PB uses") h = head print(f"{h[0]:10} {h[1]:>6} {h[2]:>7} {h[3]:>8} {h[4]:>10}") for name, k, m in schemes: over = (k + m) / k print(f"{name:10} {k + m:6} {m:7} {over:7.2f}x {over * PB:8.2f} PB")
l5b_run.py: overhead for 1 PB of logical data
scheme pieces lost ok overhead 1 PB uses 3 copies 3 2 3.00x 3.00 PB XOR 4+1 5 1 1.25x 1.25 PB 6+3 code 9 3 1.50x 1.50 PB 10+4 code 14 4 1.40x 1.40 PB
Disk saved by the code: 1.60 PB (3.00 PB minus 1.40 PB, from the run)
Read it as steps
The same petabyte stored with replication and with an erasure code.
Erasure coding is not free. To rebuild one lost piece of a 10+4 code you must read 10 other pieces, so repair moves about ten times the data of a copy. A read that finds a piece missing must collect pieces from several nodes, which is slower than reading a copy. Small objects fit badly, because pieces become tiny. Stores therefore use replication for hot data and small objects, and erasure coding for large, older, rarely read data.
Part 6 · Deleting, garbage collection and signed URLs
Delete and garbage collection
Deleting a blob looks simple and has a trap. The blob's chunks sit on several data nodes, and a delete that tries to remove them all at once can fail halfway, leaving a key that points to missing chunks. Most stores split the delete in two.
First, the metadata service removes the key, or marks it with a tombstone, the delete marker of the key-value store chapter. From that moment readers cannot see the blob, and the delete has happened as far as any client can tell. Second, a background job called the garbage collector finds chunks that no live object refers to and removes them from the data nodes. If the collector is slow or the node is down, nothing is visible to users, and the space is reclaimed later.
The collector needs a grace period. A chunk that was just written for an upload that has not completed yet is also unreferenced, and removing it would break that upload. So the collector only removes unreferenced chunks that are older than the grace period. Chunks of abandoned multipart uploads are also removed by the same job or by a lifecycle rule, as the earlier lesson noted.
GRACE = 60 # seconds a new chunk is protected objects = {"a": ["c1", "c2"], "b": ["c3"]} # key -> chunk ids # chunk id -> time created; c9 belongs to an abandoned upload chunks = {"c1": 0, "c2": 0, "c3": 0, "c9": 0, "c10": 95} def delete(key): objects.pop(key, None) # metadata first: now invisible def sweep(now): live = {c for ids in objects.values() for c in ids} gone = [c for c, born in chunks.items() if c not in live and now - born > GRACE] for c in gone: del chunks[c] return gone delete("a") print("after delete, chunks still on disk:", sorted(chunks)) print("sweep at t=100 removes:", sweep(100)) print("left:", sorted(chunks))
l6b_run.py: delete, then sweep with a grace period
after delete, chunks still on disk: ['c1', 'c10', 'c2', 'c3', 'c9'] sweep at t=100 removes: ['c1', 'c2', 'c9'] left: ['c10', 'c3']
After delete("a"), the chunks c1 and c2 are still on disk, because deleting the key only touched the metadata. At time 100 the sweep removed c1 and c2, and also c9, a chunk that was never part of any object and is now old. It left c3, which object b still uses, and c10, which is only 5 seconds old and so inside the grace period.
Signed URLs
Objects are private by default. The S3 documentation says only the object owner has access, and that the owner can share an object with a presigned URL, which carries credentials in it and grants time-limited permission. This lets a mobile app download or upload a blob directly from the store, with no bytes passing through your own servers.
The idea is a signature. The server that issues the URL computes an HMAC, a keyed hash, over the method, the path and an expiry time, using a secret key that only the store and the issuer know. The URL carries the expiry and the signature. When the request arrives, the store recomputes the HMAC. If it matches and the expiry has not passed, the request is allowed. Nobody without the secret can make a valid signature, and changing the path, the method or the expiry breaks it.
The S3 documentation gives a maximum lifetime of 7 days for a presigned URL made with the AWS CLI and 12 hours for one made in the console. The credentials behind the URL are those of the user who made it. A short lifetime limits the damage if a URL leaks.
import hashlib, hmac from urllib.parse import urlsplit, parse_qs SECRET = b"demo-secret-not-a-real-key" def sign(method, path, expires): msg = f"{method}\n{path}\n{expires}".encode() return hmac.new(SECRET, msg, hashlib.sha256).hexdigest() def make_url(method, path, now, ttl): expires = int(now + ttl) return f"{path}?expires={expires}&sig={sign(method, path, expires)}" def check(method, url, now): u = urlsplit(url) q = parse_qs(u.query) expires, sig = int(q["expires"][0]), q["sig"][0] if now > expires: return "rejected: expired" if not hmac.compare_digest(sig, sign(method, u.path, expires)): return "rejected: bad signature" return "accepted"
signing.py: sign and check a URL
The check compares signatures with hmac.compare_digest, which takes the same time whatever the input, so an attacker cannot learn the signature one character at a time from response times. The secret in the code is a demonstration value and not a real key.
Run: valid, expired and tampered
The run issues a GET URL for /photos/a.jpg at time 1000, valid for 300 seconds, so it expires at 1300. It then checks the URL at several times and with several changes. The time is passed in as a number, so the run is repeatable.
from signing import make_url, check url = make_url("GET", "/photos/a.jpg", now=1000, ttl=300) print(url[:48] + "...") print("t=1100, GET:", check("GET", url, 1100)) print("t=1300, GET:", check("GET", url, 1300)) print("t=1301, GET:", check("GET", url, 1301)) print("PUT with the GET url:", check("PUT", url, 1100)) other = url.replace("a.jpg", "b.jpg") print("another key:", check("GET", other, 1100)) longer = url.replace("expires=1300", "expires=9999") print("longer expiry:", check("GET", longer, 1100))
l6_run.py: five checks of one URL
/photos/a.jpg?expires=1300&sig=b4831efadbd1f6dda... t=1100, GET: accepted t=1300, GET: accepted t=1301, GET: rejected: expired PUT with the GET url: rejected: bad signature another key: rejected: bad signature longer expiry: rejected: bad signature
The signature is cut after 48 characters for display.
The URL worked at 1100 and still at 1300, the moment of expiry, and was refused at 1301. A PUT with the GET URL was refused, so a link for reading cannot be used for writing. Changing the key, or extending the expiry to 9999, was refused, because each change makes the signature wrong.
The same pattern serves uploads. A front end checks that the user may upload, issues a signed PUT URL for a new key, and the client sends the bytes straight to the store. That keeps large transfers off the application servers, which is why upload flows for photos and video are built this way.
Why does the garbage collector ignore chunks younger than the grace period?
- An unreferenced young chunk may belong to an upload that has not completed, and removing it would break that upload.
A signed URL for GET is changed to use PUT. Why is it refused?
- The method is part of the signed text, so the recomputed signature differs from the one in the URL.