Core Concepts

Object Storage (S3)

Store large files as durable objects and retrieve them by key.

Free~18 min

Object storage stores file bytes under a key so an application can fetch them later. Keep large payloads such as videos, images, and backups in object storage. Keep fields the application searches or joins, such as owner, title, and publication state, in a database.

This guide uses Amazon S3 general purpose buckets. We will follow a video for lesson 42 from upload to playback.

Decide where the bytes belong

A database can store binary data, sometimes called a BLOB, short for binary large object. That can be practical when a small payload must commit with its row. For a large video, storing the bytes in PostgreSQL can increase storage, write-ahead log traffic, and backup volume. It also puts video transfers on the database's read path.

Store the video in S3 and its title, lesson ID, status, and object key in PostgreSQL. This lets us query which videos a user can watch with a small database read. Video bytes travel only when the user requests playback.

Fetch by key and list by prefix

An S3 bucket groups objects. Within the bucket, the key identifies an object. The video is stored at lessons/42/u7.mp4 in an example bucket named lesson-media-example. Here, u7 is the identifier for this upload. The slashes are ordinary characters. A prefix such as lessons/42/ matches keys that begin with that text. Tools can display those prefixes as folders.

An operator can use ListObjectsV2 to inspect the lesson's stored media. This example requests one page with at most one key. --no-paginate keeps the AWS CLI from making additional requests.

aws s3api list-objects-v2 \
  --bucket lesson-media-example \
  --prefix lessons/42/ --max-keys 1 --no-paginate

Selected fields from the first response

{
  "IsTruncated": true,
  "Contents": [{"Key": "lessons/42/u7.mp4"}],
  "NextContinuationToken": "<opaque token>"
}

Pass NextContinuationToken back as the continuation token to get the next page. S3 can return up to 1,000 keys in each response. The playback service already has the full key, so it can go straight to GetObject. A prefix is useful for batch cleanup, lifecycle rules, or policies that apply to a group of keys. S3 ListObjectsV2

A plain PUT at the same key writes a new whole object. Subsequent reads and listings in the source bucket reflect successful writes and deletes. A read racing an overwrite sees either complete object. To replace a specific current object, send its entity tag, or ETag, in the If-Match header. That precondition checks one object. S3 data consistency · S3 conditional writes

Read the row before serving the video

The application first checks that the caller can watch lesson 42, then looks up its published video. The following query uses the selected upload ID u7.

SELECT object_key, content_type
FROM lesson_videos
WHERE lesson_id = 42 AND upload_id = 'u7' AND state = 'ready';

Result after publication

object_key        | content_type
------------------+-------------
lessons/42/u7.mp4 | video/mp4

Result while the upload is pending

(0 rows)

A metadata-only screen can stop after its database read. For playback, the application signs a presigned URL for GET on this exact key. The URL lets whoever holds it make that request while it is valid. The client fetches the bytes from S3. S3 can serve a byte range when the player needs a portion of the video. S3 presigned URLs · S3 GetObject

Playback request for the first 1,024 bytes (signature parameters omitted)

GET /lessons/42/u7.mp4 HTTP/1.1
Host: lesson-media-example.s3.us-east-1.amazonaws.com
Range: bytes=0-1023

S3 response (video bytes omitted)

HTTP/1.1 206 Partial Content
Content-Type: video/mp4
Content-Range: bytes 0-1023/125829120
Content-Length: 1024

Keep an upload recoverable

Suppose the application commits a database row before the bytes reach S3. A server crash can leave the row pointing to a missing object. Reversing the order can leave an object with no row if the database transaction fails. S3 and PostgreSQL have separate commit boundaries.

Store a recoverable copy first

After authorizing the upload, the server reserves a unique staging key for u7, records the expected byte length and checksum with the upload session, and signs a PUT for that key in the private bucket. Staging is where we keep the bytes before playback is allowed. The request below shows selected headers and an illustrative checksum. The presigned query parameters and video body are omitted.

PUT /staging/lessons/42/u7.mp4 HTTP/1.1
Host: lesson-media-example.s3.us-east-1.amazonaws.com
Content-Type: video/mp4
Content-Length: 125829120
If-None-Match: *
x-amz-checksum-crc32c: EjRWeA==

Response when the upload succeeds

HTTP/1.1 200 OK

The first request might succeed and lose its reply. If the client retries that same request while the URL is valid, the condition says to create the object only if the key has no current object. The first upload left an object there, so S3 can return the following response.

HTTP/1.1 412 Precondition Failed

A 412 establishes that the key is occupied. The server authorizes the session and uses HeadObject with checksum mode enabled to compare the stored length and checksum with what it recorded for u7. The checksum checks transfer integrity. A match lets the server proceed even when the browser missed the first reply. Otherwise it rejects finalization. Sign the required headers or enforce the conditional write with a bucket policy. Keep the verified source protected from writes and early deletion. With versioning enabled, the worker can pin the verified version ID. S3 conditional writes · S3 HeadObject

Commit the intent, then publish

Once the bytes are verified, write the pending video row and a finalize_upload event in one PostgreSQL transaction. The event names the verified staging source and the final key reserved for u7. This is a transactional outbox. The database commits the pending state and the instruction to finish it together. An outbox event can refer to durable bytes after a process crashes. It cannot recover a request body that was only in memory.

Follow the diagram from the first durable write through the worker's final database update.

The worker uses S3 CopyObject for this 120 MiB file. Once the copy succeeds, it uses a conditional database update to change pending to ready. If it crashes after the copy, a retry can copy the same protected source to the same reserved destination and finish the state update. Keep the staging object while the row is pending. A single CopyObject supports objects up to 5 GB. Larger objects require multipart copy. S3 CopyObject

When the retry window expires, a cleanup job can conditionally change pending to failed. Only one of those database transitions can win. If a copy finishes after the failure transition, the private final object stays hidden because playback requires a ready row. Sweep abandoned keys again after in-flight copies finish and signed upload URLs expire. This also covers an upload that reached staging before the database transaction failed.

Retry a large upload in parts

A single PUT resends the whole file on a network retry. For the same 120 MiB video, a multipart upload can send three 40 MiB parts independently. This is another way to store the same staging object before the verification step.

Start the upload and choose CRC32C as the checksum for the whole file.

aws s3api create-multipart-upload \
  --bucket lesson-media-example \
  --key staging/lessons/42/u7.mp4 --content-type video/mp4 \
  --checksum-algorithm CRC32C --checksum-type FULL_OBJECT

Save the returned UploadId as UPLOAD_ID. It identifies the set of staged parts for this attempt. If part 2 times out, retry the same byte range with the same upload ID and part number. A later successful write for that part number replaces its previous contents. The HTTP excerpts omit signing details and the body. The ETags and checksum values illustrate the format. Use the values from your own upload.

PUT /staging/lessons/42/u7.mp4?partNumber=2&uploadId=<upload-id> HTTP/1.1
Host: lesson-media-example.s3.us-east-1.amazonaws.com
Content-Length: 41943040

Part 2 response

HTTP/1.1 200 OK
ETag: "3d94ab596caefa9f19d34a210b3d9fbc"

Record the ETag returned for each successful part. The following parts.json lists all three in order. These ETags identify part results for completion. We pass the recorded full-object checksum and byte length so S3 verifies the assembled file. S3 multipart upload · S3 upload checksums

{
  "Parts": [
    {"PartNumber": 1, "ETag": "\"0cc175b9c0f1b6a831c399e269772661\""},
    {"PartNumber": 2, "ETag": "\"3d94ab596caefa9f19d34a210b3d9fbc\""},
    {"PartNumber": 3, "ETag": "\"92eb5ffee6ae2fec3ad71c777531578f\""}
  ]
}

Complete the upload

aws s3api complete-multipart-upload \
  --bucket lesson-media-example \
  --key staging/lessons/42/u7.mp4 \
  --upload-id "$UPLOAD_ID" --multipart-upload file://parts.json \
  --checksum-type FULL_OBJECT --checksum-crc32-c EjRWeA== \
  --mpu-object-size 125829120 \
  --if-none-match '*'

Selected fields from a successful completion

{
  "Bucket": "lesson-media-example",
  "Key": "staging/lessons/42/u7.mp4"
}

S3 assembles the parts in part-number order when completion succeeds. If using raw HTTP, inspect the body of the completion response. S3 can start sending a 200 OK before it knows whether completion succeeded. AWS SDKs handle that embedded-error case. S3 CompleteMultipartUpload

S3 retains uploaded parts until completion or abort. A bucket lifecycle rule can abort abandoned incomplete uploads. Completed staging objects have their own cleanup path based on the application state.

Archive old lesson views

The video is retrieved by key, and its view events have a different access pattern. Recent view events are useful in a dashboard, where PostgreSQL can filter them by lesson and time. A sealed daily partition, one that no longer accepts writes, can move to a cold tier that lowers storage cost for data read infrequently.

Export the partition for February 14, 2026 to archive/lesson-views/2026-02-14.parquet. Parquet groups values by column so an analytics engine can read selected fields without loading every field from each row. Reopen the archive, check that the file is readable, and reconcile its checksums and row counts against the sealed export. Then update a catalog that tells readers where that date lives. Let old readers finish before removing the database partition. Apache Parquet format

Keep archives in a directly readable storage class when old queries still need a prompt response. S3 Glacier Flexible Retrieval and Deep Archive require a restore before you can read the bytes. Count retrieval costs and restore time as well as storage savings. Restoring S3 archives

How to use in a system design

For a course platform, choose S3 for large videos and PostgreSQL for author, lesson, and publication queries. A small asset whose bytes must commit with its row can stay in the database. Issue short-lived URLs after checking access so the application handles permissions and S3 handles bulk transfers. Choose multipart upload when retries on large files would otherwise waste time and bandwidth.

Explain what a learner sees when a transfer or worker fails. Keep the video hidden until its final key is durable and its row is ready. Name the source the worker can reread, the condition that protects the staging write, and the state transition that wins against cleanup. For view history, choose the archive format and storage class from how quickly past dates need to be queryable.

See also

  • PostgreSQL - query metadata and commit publication state.
  • Transactional Outbox - commit an instruction to continue work alongside the pending state.
  • Write-Ahead Log - understand the database write and replication cost of large inline payloads.
  • Data Replication - understand why a cross-Region replica can lag the source.

Used in

  • ChatGPT - stores archived text in per-conversation objects, with an index from a conversation and sequence range to the object.
  • Collaborative Coding Interview Platform - stores run output in S3 and keeps its object key in the event log.

Done reading? Mark it so it sticks in your dashboard.

Discussion