Synthetic data. I rebuilt these utilities from scratch against public AWS APIs so the code can be public. Nothing here comes from Amazon systems.
AWS data helpers that know which environment they're in
A Python library for the S3, Glue, Athena, Redshift and Lambda code a data team writes in every job, with the target environment built into every call.
Why I built this
At Amazon I wrote a utility library in our team's Python repo for the code every pipeline needed: writing to S3 without overwriting files, building partition paths, connecting to Athena or Redshift, registering Glue partitions, checking schemas, and the setup around Lambda handlers. The whole team adopted it and used it every day instead of rewriting the same boto3 code in each job. Each function took the environment's bucket and prefix as arguments, so a job wrote to the backend it was deployed for. I wanted a version I could show, so I rebuilt it from scratch as a public library with tests.
The rebuild goes one step further. Callers pass an environment name such as "beta", and the library looks up that environment's bucket, prefix, Glue database, Athena workgroup, Redshift target and AWS account. Job code never names a bucket.
How it works
1. Every call names an environment
Job code passes an environment name and a key relative to that environment. The library looks up the bucket, prefix, Glue database and query settings. If the environment lists an AWS account, the credentials must belong to it before any client is handed out.
Loading diagram…
2. Writes that refuse to overwrite
By default a write checks whether the key exists, then sends the upload with If-None-Match: *. If another job creates the key between the check and the upload, S3 rejects the upload, so two writers can never both succeed. overwrite=True turns both checks off.
Loading diagram…
3. Example ingest Lambda
The example handler is pinned to one environment through the DATAKIT_ENV variable. It only reads files in that environment's incoming/ folder, so its own output can never trigger it. Each file is schema-checked and written as Parquet partitioned by day, under a name that comes from the source file.
Loading diagram…
Walkthrough
Every step below is in examples/walkthrough.py (opens in a new tab). It runs offline against moto, a library that mocks AWS, so it needs no AWS account. The code is trimmed slightly for reading, and the output is exactly what the script prints. Where a call raises an error, the script catches it and prints it: those are the blocked: and caught drift: lines.
Step 1: Register the environments
From here on, code only says "beta" or "prod". A real setup would also give each environment an account_id, so a job configured for beta refuses to run with production credentials. Source: src/awsdatakit/config.py (opens in a new tab).
register_config(
EnvConfig(name="beta", bucket="demo-beta", prefix="analytics", glue_database="demo"),
EnvConfig(name="prod", bucket="demo-prod", prefix="analytics", glue_database="demo"),
)Step 2: A second write to the same key is refused
The caller passes a relative key, and the library adds the environment's bucket and prefix. The second call raises ObjectExistsError and the first file is unchanged. Source: src/awsdatakit/s3.py (opens in a new tab).
print(safe_put_object("beta", "notes/hello.txt", "first"))
safe_put_object("beta", "notes/hello.txt", "second") # raises ObjectExistsErrors3://demo-beta/analytics/notes/hello.txt
blocked: s3://demo-beta/analytics/notes/hello.txt already existsThe code that makes this safe with two writers at once. Every upload also carries a SHA-256 checksum. If the SDK resends an upload whose response got lost, the resend fails the condition, and the stored checksum shows the object is this same upload, so it counts as written instead of raising.
if not overwrite:
if precheck and _exists_if_visible(cfg, key, s3):
raise ObjectExistsError(f"{uri} already exists")
kwargs["IfNoneMatch"] = "*"
try:
s3.put_object(**kwargs)
except ClientError as exc:
if overwrite or exc.response["Error"]["Code"] not in _PRECONDITION_CODES:
raise
# The key exists. If it holds exactly these bytes, this was our own write: the SDK
# retried a PUT whose response was lost, and the retry hit the condition.
if _holds_same_bytes(cfg, full_key, checksum, s3):
return uri
raise ObjectExistsError(f"{uri} already exists") from excStep 3: Partitioned Parquet, checked before anything is written
The DataFrame is split by dt into one Parquet file per day, in the Hive layout Glue and Athena expect. The partition column moves into the path. Running the same write again checks every target first and writes nothing. Source: src/awsdatakit/partitioning.py (opens in a new tab).
df = pd.DataFrame({
"order_id": [1, 2, 3], "customer": ["a", "b", "c"], "amount": [9.5, 3.0, 7.25],
"dt": ["2024-05-01", "2024-05-01", "2024-05-02"],
})
put_dataframe_partitioned("beta", "orders", df, ["dt"])
print(*list_keys("beta", "orders"), sep="\n")
put_dataframe_partitioned("beta", "orders", df, ["dt"]) # raises ObjectExistsErrororders/dt=2024-05-01/part-0000.parquet
orders/dt=2024-05-02/part-0000.parquet
blocked: 2 target(s) exist, e.g. orders/dt=2024-05-01/part-0000.parquetStep 4: Register partitions in Glue, then check the schema
Partition registration skips partitions that already exist, so rerunning a job doesn't fail. The schema check compares the DataFrame with the Glue table after normalizing type names, so pandas int64 matches Glue bigint. When amount turns into text, the check names the column and both types. Source: src/awsdatakit/glue.py (opens in a new tab) and src/awsdatakit/schema.py (opens in a new tab).
parts = [{"dt": "2024-05-01"}, {"dt": "2024-05-02"}]
print("added:", dkglue.add_partitions("beta", "orders", parts))
print("added again:", dkglue.add_partitions("beta", "orders", parts[:1]))
expected = dkglue.get_table_schema("beta", "orders")
assert_schema_matches(expected, df)
print("DataFrame matches the Glue table")
drifted = df.assign(amount=df.amount.astype(str))
assert_schema_matches(expected, drifted) # raises SchemaMismatchErroradded: 2
added again: 0
DataFrame matches the Glue table
caught drift: type mismatch on 'amount': expected double, got stringStep 5: Read it back, and confirm production was never touched
print(get_dataframe("beta", "orders/dt=2024-05-01/part-0000.parquet"))
print("prod untouched:", list(list_keys("prod"))) order_id customer amount
0 1 a 9.5
1 2 b 3.0
prod untouched: []Querying Athena and Redshift
These calls need a real AWS account, so they aren't in the walkthrough. In the repo they're tested with mock clients that assert the requests the library sends (workgroup, result location, database, parameters, and the cancel call on a timeout) and how it reads the responses. Source: src/awsdatakit/athena.py (opens in a new tab) and src/awsdatakit/redshift.py (opens in a new tab).
daily = athena.run_query(
"prod",
"SELECT dt, count(*) AS orders FROM orders WHERE dt >= ? GROUP BY dt",
params=["2024-05-01"], # sent to Athena as '2024-05-01'
)
totals = redshift.run_statement(
"prod",
"SELECT customer, sum(amount) AS total FROM orders WHERE dt = :dt GROUP BY customer",
params={"dt": "2024-05-01"},
)- Athena runs in prod's workgroup and Glue database and, by default, writes results under prod's bucket. The library polls with exponential backoff and cancels the query if it runs past the timeout.
- Parameters are never formatted into the SQL text. Athena gets quoted literals, because it would read an unquoted
2024-05-01as the number 2018. Redshift gets named parameters through the Data API. - Redshift uses the same call for a serverless workgroup or a provisioned cluster, with Secrets Manager or IAM credentials, depending on the environment config.
The Lambda handler
The decorator handles the setup every handler repeats. Source: src/awsdatakit/lambda_utils.py (opens in a new tab) and examples/lambda_ingest/handler.py (opens in a new tab).
@lambda_handler
def handler(event, context, cfg):
incoming = cfg.resolve_key("incoming/")
for bucket, key in extract_s3_records(event):
if bucket != cfg.bucket or not key.startswith(incoming) or key.endswith("/"):
continue # logged in the full example
df = get_dataframe(cfg, cfg.strip_prefix(key))
assert_schema_matches(EXPECTED, df)
put_dataframe_partitioned(cfg, "orders", df, ["dt"],
filename=output_name(key), overwrite=True)- The decorator reads
DATAKIT_ENV, which the CDK stack sets, so the function can only use the environment it was deployed for. - It logs each invocation as JSON lines, started and then finished or failed, with the request id, environment and duration.
extract_s3_recordsreturns object-created events delivered directly or through SNS, SQS, or both, and skips deletes and other S3 events.output_namehashes the source key, so the same source file always produces the same output name. A retried or redelivered event replaces those files instead of adding duplicate rows.- Errors are logged and re-raised, so Lambda retries and dead-letter queues still work. With
http=Truethe decorator returns API Gateway responses instead: 400 for a bad key, 422 for schema drift, 409 for an existing object, and a generic 500 for any other error, including a missing environment, so bucket names, account IDs and SQL errors stay in the logs.
The example is tested end to end against moto, including two files in one event, a redelivered event, and keys outside incoming/.
What it handles
- The wrong environment: functions take an environment name, never a bucket.
- The wrong account: if an environment sets
account_id, the library checks the credentials with STS before it hands out any client. - Overwrites are refused unless the caller passes
overwrite=True. - Two writers, one key: S3 rejects the second upload because of
If-None-Match: *. This still works for a role withouts3:ListBucket, which can't run the existence check. - Lost responses: if the SDK resends an upload whose response got lost, the stored SHA-256 checksum shows it's the same upload, so the write succeeds instead of reporting the file as already there.
- Missing partition values: a write with any null partition value fails before anything is written, instead of silently leaving those rows out.
- Keys that escape the prefix: keys with a
..path segment or a backslash, empty keys, and partition values that would add a folder are rejected. - Reruns: Glue partition registration sends every requested partition in batches of 100 and treats "already exists" as success, so it never lists the table's partitions and stays fast on large tables.
- Schema drift: missing, extra and mistyped columns are reported by name. Column order is checked too when you pass
check_order=True. - Slow or stuck queries: Athena and Redshift polling backs off exponentially, and a timeout cancels the query.
- Throttling and threads: clients use boto3's adaptive retry mode, and each environment's clients are created under a lock, so a thread pool can share them safely.
Tools and where they're used
- Python 3.11+, boto3, pandas and pyarrow: the library itself
- Amazon S3: no-overwrite writes, reads, listing, and partitioned Parquet
- AWS Glue Data Catalog: table schemas, partition registration, and crawler runs
- Amazon Athena and the Redshift Data API: parameterized queries with polling and timeouts
- AWS Lambda: the handler decorator and the example ingest function
- AWS STS: assume-role sessions and the account check
- AWS CDK (Python): one stack per environment with a versioned, encrypted bucket, a Glue database, an Athena workgroup with a 10 GB scan limit per query, and the example Lambda with S3 access limited to its two folders and 30-day log retention
- pytest and moto: 70 tests. moto mocks S3, Glue and STS; Athena and Redshift use mock clients
- ruff, mypy (strict) and GitHub Actions: lint, type checks, tests and the walkthrough for every push, on Python 3.11 with pandas 2 and 3, and on Python 3.14
Trade-offs I made
- Environment names instead of bucket names. Every project needs an environment config up front. In return, the same job code runs in beta and production unchanged.
- One HEAD request per file. The existence check costs a request for each file, but it gives a clear error before uploading. The conditional upload covers the race the check alone can't.
- All-or-nothing, but only before writing. A partitioned write checks every target first. If the process dies partway through the writes, some partitions can be written and others not. Rerunning with
overwrite=Truerepairs it. - The example Lambda overwrites on purpose. The library refuses overwrites by default, but the Lambda's output names come from its source files, so replacing them is what makes a redelivered event safe. Refusing would fail the retry, and fresh names would duplicate rows. This treats source files as immutable: a correction should arrive as a new file, because a re-upload under the same name only replaces the days it still contains.
- Strings out of Athena. Athena returns every value as text, and NULL as
None. The library doesn't guess types: callers cast, for example using the Glue table's schema. - Mocks for Athena and Redshift. moto can't execute SQL, and it doesn't yet route the protocol current boto3 versions use for Athena. Those tests check the requests the library sends and how it reads canned responses, not real query results.
I haven't deployed the CDK stack. It synthesizes, but the example Lambda still needs a layer with awsdatakit, pandas and pyarrow, and an S3 or SQS trigger filtered to the incoming/ folder, before it can run on AWS.
Run it yourself
The library, tests, walkthrough and CDK stack are on GitHub: timothypike/awsdatakit (opens in a new tab). None of this needs an AWS account.
git clone https://github.com/timothypike/awsdatakit && cd awsdatakit
python3 -m venv .venv && source .venv/bin/activate # Python 3.11 or newer
pip install -e ".[dev]"
pytest -q # 70 tests
python examples/walkthrough.py # the steps on this pageWorking through a similar problem?
Discuss a project →