Sub topic 3
Objects, Keys and Prefixes
This chapter assumes you can run basic AWS CLI commands, have created a bucket (see the previous chapter), and can read short Python snippets. It explains what an S3 object is, how its key works, and how to design key names so that listing and access stay predictable.
What an object contains
An object is the unit of data in S3. Each object has these parts:
- Key: the name that identifies the object inside its bucket.
- Value: the bytes you stored. A single object can be from 0 bytes up to 5 TB.
- Metadata: system metadata such as
Content-Type,Content-LengthandETag, plus optional user-defined metadata you set at upload time. - Version ID: present when versioning is enabled. Without versioning, it is
null. - Tags: up to 10 key-value pairs per object, usable in access policies and lifecycle rules.
The bucket name plus the key identify one object. S3 has no "update part of an object" operation. To change an object you write a whole new object under the same key, and the new one replaces the old one (or becomes a new version if versioning is on).
Keys are flat strings, not paths
A key is a UTF-8 string of up to 1,024 bytes. S3 does not store a directory tree. The bucket is a flat map from key to object, and a key such as reports/2026/report.csv is a single string that happens to contain slashes.
The console and many tools show folders. They do this by treating / as a separator when they display keys. A "folder" is only a display convention built on shared key beginnings.
Consequences of the flat model:
- Creating
reports/2026/report.csvdoes not require creatingreports/orreports/2026/first. - Deleting the last object under a prefix makes the "folder" disappear, because it never existed as a separate thing.
- There is no rename. Renaming means copying to a new key and deleting the old one.
- Moving a "folder" means copying and deleting every object that shares the prefix.
Folder placeholder objects
If you click "Create folder" in the console, S3 creates a zero-byte object whose key ends in /, such as reports/. This is a normal object that tools use as a marker. It shows up in listings and can confuse code that expects every key to be a real file. Skip keys that end in / when you process listings.
Prefixes and delimiters
A prefix is the leading part of a key, used to select a group of objects. A delimiter is a character, normally /, that tells S3 to roll up keys into groups when you list.
The listing API accepts both. Given these keys:
reports/2026/report.csvreports/2026/summary.csvreports/2025/report.csvlogs/app.log
The results depend on the parameters:
| Request | Result |
|---|---|
| Prefix `reports/` with no delimiter | All three `reports/` objects, listed in full |
| Prefix `reports/` with delimiter `/` | Common prefixes `reports/2025/` and `reports/2026/`, no objects |
| Prefix `reports/2026/` with delimiter `/` | The two objects under `reports/2026/` |
| No prefix with delimiter `/` | Common prefixes `reports/` and `logs/` |
Prefix matching is plain string matching. Prefix reports/20 matches both reports/2025/... and reports/2026/.... Prefix report without the slash would also match a key named reports-old/a.txt. Include the trailing slash when you mean a folder.
Working with keys in practice
The CLI's high-level aws s3 commands add folder-like behavior. The lower-level aws s3api commands expose the raw API.
aws s3 cp report.csv s3://my-example-bucket-123456789012/reports/2026/report.csv
# Folder-like view: one level, with PRE lines for common prefixes
aws s3 ls s3://my-example-bucket-123456789012/reports/
# Raw API: list keys with a delimiter and read the grouped prefixes
aws s3api list-objects-v2 \
--bucket my-example-bucket-123456789012 \
--prefix reports/ \
--delimiter /In boto3, list_objects_v2 returns at most 1,000 keys per call. Use a paginator so you do not silently miss objects.
import boto3
s3 = boto3.client("s3")
bucket = "my-example-bucket-123456789012"
paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=bucket, Prefix="reports/", Delimiter="/"):
for common in page.get("CommonPrefixes", []):
print("prefix:", common["Prefix"])
for obj in page.get("Contents", []):
if obj["Key"].endswith("/"):
continue # skip folder placeholder objects
print("object:", obj["Key"], obj["Size"])Two details matter here. When you pass a delimiter, subfolders arrive in CommonPrefixes and files arrive in Contents, so you must read both. Also, Contents is absent from a page with no objects, which is why the code uses .get(..., []).
Listings return keys in ascending UTF-8 binary order. This is not numeric order, so file10 sorts before file2. Zero-pad numbers (file002) or use ISO dates (2026-03-07) when you want listings to sort naturally.
Choosing good key names
Design keys around the questions you will ask when you list or filter. Listing works by prefix, so the part of the key you filter on most often should come first.
Guidelines:
- Put stable, high-level grouping first. For example
tenant-42/2026/03/07/events.jsonlets you list one tenant, or one tenant and one month, with a simple prefix. - Use ISO-style dates.
2026/03/07or2026-03-07sorts chronologically and supports prefix queries by year or month. - Avoid characters that need special handling. Letters, digits,
/,!,-,_,.,*,',(and)are safe. Spaces,&,$,@,=,;,:,+,,and?often need URL encoding, and some characters can be mishandled by other tools. - Do not use
.or..path segments. Keys such asa/../bare valid strings but break many clients that normalize paths. - Keep keys short enough to read in logs and policies. The hard limit is 1,024 bytes, and multi-byte characters use more than one byte each.
- Do not put sensitive data in keys. Keys appear in access logs, event notifications and listings, which are often visible to more people than the object contents.
Prefixes and request rates
S3 scales request throughput per prefix. Each prefix supports at least 3,500 write requests (PUT, COPY, POST, DELETE) and 5,500 read requests (GET, HEAD) per second, and a bucket can hold any number of prefixes. S3 partitions automatically as traffic grows, so you no longer need to add random characters at the front of keys to avoid hot spots. If you expect very high request rates, spreading load across several prefixes raises the total available rate. A sudden jump to a high rate on a new prefix can briefly return 503 Slow Down while S3 scales, so clients should retry with exponential backoff, which the AWS SDKs do by default.
Prefixes in access control
Prefixes are also the main way to scope permissions. An IAM policy can grant access to one prefix by using a resource ARN such as arn:aws:s3:::my-example-bucket-123456789012/tenant-42/*. Listing is a bucket-level action, so to limit who can list a prefix you add an s3:prefix condition on s3:ListBucket. A later chapter covers this in detail. The point for now is that your key layout becomes your permission layout, so decide the layout before you write policies.
Metadata, content type and ETag
System metadata travels with the object. Content-Type controls how browsers treat a download. upload_file guesses the type from the extension, but put_object does not, so set it yourself when it matters.
import boto3
s3 = boto3.client("s3")
bucket = "my-example-bucket-123456789012"
s3.put_object(
Bucket=bucket,
Key="reports/2026/summary.json",
Body=b'{"total": 42}',
ContentType="application/json",
Metadata={"owner": "finance"},
)
head = s3.head_object(Bucket=bucket, Key="reports/2026/summary.json")
print(head["ContentType"], head["ContentLength"], head["ETag"])
print(head["Metadata"])head_object reads metadata without downloading the body. User-defined metadata is returned with the x-amz-meta- prefix removed and lowercased. Metadata cannot be edited in place. To change it, copy the object onto itself with MetadataDirective="REPLACE", which creates a new object.
The ETag is an identifier for a specific content version. For simple uploads without KMS or customer-provided keys it is the MD5 hash of the data. For multipart uploads and some encryption modes it is not an MD5 of the whole file, so do not rely on it as a checksum. Use S3's additional checksums (such as SHA-256) if you need integrity verification.
Deleting objects
Deleting an object by key removes it, or, with versioning enabled, adds a delete marker. A delete of a key that does not exist still succeeds. You can delete up to 1,000 keys in a single delete_objects call.
aws s3 rm s3://my-example-bucket-123456789012/reports/2026/report.csv
# Remove everything under a prefix
aws s3 rm s3://my-example-bucket-123456789012/reports/ --recursiveReview a --recursive delete with --dryrun first. Because a prefix is only a string match, --recursive on reports (no slash) also removes reports-old/....
Common errors
| Symptom | Likely cause |
|---|---|
| Listing shows fewer objects than expected | Not paginating past 1,000 keys |
| A "folder" appears that has no files | A zero-byte placeholder key ending in `/` |
| `NoSuchKey` right after typing a path | Case, spacing or leading slash differences. A key `/a.txt` differs from `a.txt` |
| Files sort as `1, 10, 2` | Binary key order, so zero-pad numbers |
| `Prefix` matches unrelated objects | Missing trailing slash in the prefix |
Exercise
A bucket contains the keys data/2026/a.csv, data/2026/b.csv, data/2025/a.csv and data-archive/old.csv. What does list_objects_v2 return for Prefix="data" with Delimiter="/", and what changes if you use Prefix="data/" instead?
Show answer
With Prefix="data" and delimiter /, S3 matches every key that begins with the string data, including data-archive/old.csv. It returns the common prefixes data-archive/ and data/, and no objects. With Prefix="data/" it matches only the three keys under data/, and returns the common prefixes data/2025/ and data/2026/. The trailing slash is what limits the match to one folder.
Exercise
Why can a Python script that lists a bucket with a single list_objects_v2 call give wrong results, and how do you fix it?
Show answer
One call returns at most 1,000 keys, so a larger listing is truncated without an error. Use s3.get_paginator("list_objects_v2") and iterate over its pages, or follow NextContinuationToken manually. Also read CommonPrefixes when you pass a delimiter.