The Spark, Airflow, SQL, AWS, Docker and shell code I have looked up more than twice — copied out of jobs that run in production, not invented for a blog post. Every one of them carries the caveat that made me learn it: the config that quietly deletes a table, the join that OOMs the driver, the sensor that holds a worker slot for six hours doing nothing.
Write partitioned Parquet, replacing only the partitions you touched
Dynamic partition overwrite so a daily rerun replaces one date instead of deleting the whole table.
PySparkPython
# Only the partitions present in the DataFrame get replaced. Without this,# mode("overwrite") deletes everything under the path first.
spark.conf.set("spark.sql.sources.partitionOverwriteMode","dynamic")(df
.repartition("event_date")# one file group per partition.write
.mode("overwrite").partitionBy("event_date").option("compression","snappy").parquet("s3://lake/curated/orders/"))
Watch out
partitionOverwriteMode=dynamic is the difference between replacing one day and wiping the table — test it on a copy before you trust it in production. Repartitioning by the partition column is what stops each partition being split across every task and producing thousands of tiny files, but if one date is far larger than the rest you get one huge task; use repartition(n, 'event_date') then. This setting does not apply to the legacy Hive INSERT OVERWRITE path on every engine, so verify on yours.
Read with an explicit schema instead of inferring one
Pin the schema and fail fast, so one malformed file cannot silently change a column's type downstream.
PySparkPython
from pyspark.sql.types import(
StructType, StructField, StringType, LongType, TimestampType, DecimalType,)
orders =StructType([StructField("order_id",StringType(), nullable=False),StructField("customer_id",StringType(), nullable=False),StructField("amount",DecimalType(18,2), nullable=True),StructField("created_at",TimestampType(), nullable=True),StructField("qty",LongType(), nullable=True),])
df =(spark.read
.schema(orders).option("mode","FAILFAST")# abort on the first malformed record.json("s3://lake/raw/orders/dt=2026-08-27/"))
Watch out
Schema inference on JSON reads the whole input an extra time and will happily change a column's type between runs — one file where amount arrives quoted and every downstream cast breaks. If you would rather quarantine bad rows than fail the DAG, use mode PERMISSIVE and add a _corrupt_record StringType column to the schema — without that column in the schema Spark silently drops the malformed rows instead of surfacing them. Use DecimalType for money, never DoubleType.
Broadcast the small side of a join
Ship a small dimension to every executor and skip the shuffle on the fact table entirely.
PySparkPython
from pyspark.sql.functions import broadcast
# 400 GB fact, 40 MB dimension: send the dimension everywhere and leave the# fact table where it already is.
enriched = fact.join(broadcast(dim), on="product_id", how="left")# Auto-broadcast kicks in below this threshold (default 10 MB). Raise it when# your dimensions are a little bigger and the table statistics are trustworthy.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold",64*1024*1024)
enriched.explain()# expect BroadcastHashJoin, not SortMergeJoin
Watch out
The broadcast side is collected to the driver before it is sent out, so driver memory and spark.driver.maxResultSize are the real ceiling — 100-200 MB is about as far as this goes comfortably. Broadcasting the wrong side turns a fast join into a driver OOM. Always confirm with explain() rather than assuming the hint was honoured; Spark silently ignores it when the side is genuinely too big.
Window functions: sequence, previous row, running total
row_number, lag and a framed running sum over one partitionBy/orderBy window in PySpark.
PySparkPython
from pyspark.sql import Window
from pyspark.sql import functions as F
by_customer = Window.partitionBy("customer_id").orderBy("created_at")
running = by_customer.rowsBetween(Window.unboundedPreceding, Window.currentRow)
out =(orders
.withColumn("order_seq", F.row_number().over(by_customer)).withColumn("prev_order_at", F.lag("created_at").over(by_customer)).withColumn("days_since", F.datediff("created_at", F.col("prev_order_at"))).withColumn("ltv_to_date", F.sum("amount").over(running)))
Watch out
A window with partitionBy shuffles on that key, so a customer with millions of rows becomes one enormous task — check the key distribution before you ship it. A window with orderBy and no explicit frame defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which lumps together every row sharing a timestamp; say rowsBetween when you mean rows. A window with no orderBy at all frames the whole partition, which is usually what you want for a partition-level total.
Break up a skewed join key with a salt
Spread one hot join key across N reducers by salting the fat side and replicating the thin side.
PySparkPython
from pyspark.sql import functions as F
# Find out whether you actually have skew before doing any of this.
fact.groupBy("customer_id").count().orderBy(F.desc("count")).show(20,False)
SALT =16# more buckets = more parallelism, but N copies of the small side# Fat side: give every row a random bucket.
fact_salted = fact.withColumn("_salt",(F.rand()* SALT).cast("int"))# Thin side: replicate each row once per bucket.
dim_salted = dim.withColumn("_salt", F.explode(F.array([F.lit(i)for i inrange(SALT)])))
joined =(fact_salted
.join(dim_salted,["customer_id","_salt"],"left").drop("_salt"))
Watch out
Try adaptive query execution first: spark.sql.adaptive.enabled and spark.sql.adaptive.skewJoin.enabled split skewed partitions automatically on Spark 3.x and cost you nothing to turn on. Hand-rolled salting is for the cases AQE misses — a skewed aggregation, or a skewed key on the build side of a broadcast. It multiplies the small side by SALT, so keep SALT modest and never salt two large tables against each other.
repartition vs coalesce, and fixing the small-file problem
When a full shuffle is worth it, when it is not, and how to let AQE size output files for you.
PySparkPython
# repartition: full shuffle, evenly sized partitions, can go up or down.
df.repartition(200,"event_date")# coalesce: no shuffle, merges partitions in place, can only go DOWN — and it# also collapses the parallelism of the stage that produces the data.
df.coalesce(10).write.parquet(path)# Better than guessing a number: let AQE size the output partitions.
spark.conf.set("spark.sql.adaptive.enabled","true")
spark.conf.set("spark.sql.adaptive.coalescePartitions.enabled","true")
spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes","128MB")
Watch out
coalesce(1) before a write does not just produce one file, it makes the whole upstream stage run with a single task. If you need one output file from a big job use repartition(1) instead: it keeps the upstream wide and pays for exactly one shuffle. Target 128-512 MB per output file. Thousands of 2 MB Parquet files cost more in S3 LIST calls, task scheduling and driver memory than the compute ever did, and they are the single most common reason a well-tuned job is still slow.
Upsert a CDC stream into a Delta table
MERGE inserts, updates and deletes into Delta with a partition predicate so it does not rewrite the world.
PySparkPython
from delta.tables import DeltaTable
target = DeltaTable.forPath(spark,"s3://lake/curated/customers")(target.alias("t").merge(
source=updates.alias("s"),# The partition predicate is what lets Delta prune files. Without it# every merge reads and rewrites the entire table.
condition="t.customer_id = s.customer_id AND t.dt >= '2026-08-01'").whenMatchedDelete(condition="s._op = 'D'").whenMatchedUpdateAll(condition="s._op = 'U'").whenNotMatchedInsertAll(condition="s._op != 'D'").execute())
Watch out
Deduplicate the source down to one row per key first or Delta raises a MERGE cardinality violation — a CDC batch almost always contains several versions of the same row. Watch the merge become the slowest task in the DAG once the target passes a few hundred GB; that is the signal to revisit partitioning or switch to a partition-scoped replace. Deletion vectors (Delta 2.4 and later) make row-level changes far cheaper on wide tables, but every engine that reads the table has to understand them.
Read a large RDBMS table in parallel over JDBC
Slice a source table across N connections with partitionColumn, and push the filter into the database.
PySparkPython
query ="""(
SELECT id, customer_id, amount, updated_at
FROM public.orders
WHERE updated_at >= '2026-08-01'
) AS q"""
df =(spark.read
.format("jdbc").option("url","jdbc:postgresql://db.internal:5432/orders").option("dbtable", query).option("user", user).option("password", password).option("driver","org.postgresql.Driver").option("partitionColumn","id")# numeric / date / timestamp only.option("lowerBound",1).option("upperBound",50000000).option("numPartitions",16)# = 16 concurrent DB connections.option("fetchsize",10000).load())
Watch out
numPartitions is a promise of that many simultaneous connections to a production database — agree the number with whoever owns it before you run this at 2am. lowerBound and upperBound only decide how the id range is sliced, they do not filter: rows below the lower bound land in the first partition and rows above the upper bound in the last, so a badly chosen upperBound recreates the skew you were trying to avoid. Push the WHERE into the subquery so the database filters, not Spark.
Keep the latest version of each row
row_number over a partition with a deterministic tiebreaker — the CDC-safe alternative to dropDuplicates.
PySparkPython
from pyspark.sql import Window
from pyspark.sql import functions as F
latest = Window.partitionBy("order_id").orderBy(
F.col("updated_at").desc(),
F.col("_ingest_seq").desc(),# deterministic tiebreaker)
deduped =(raw
.withColumn("_rn", F.row_number().over(latest)).filter(F.col("_rn")==1).drop("_rn"))
Watch out
dropDuplicates(['order_id']) keeps an arbitrary row: fine for exact duplicates, wrong for CDC where you want the newest version. The tiebreaker is not optional either — two events in the same millisecond will flip between runs without one, and your table stops being reproducible. Use whatever monotonic value the source gives you: a Kafka offset, a binlog position, an ingest sequence, or input_file_name() as a last resort.
Replace a row-at-a-time Python UDF
Native column expressions stay in the JVM and stay visible to Catalyst; pandas_udf recovers most of the rest.
PySparkPython
from pyspark.sql import functions as F
from pyspark.sql.functions import pandas_udf
import pandas as pd
# Slow: every row crosses the JVM <-> Python boundary one at a time, and the# optimiser cannot see through it.# @F.udf("double")# def net(amount, discount): return amount - discount# Fast: native expression, pushed down and constant-folded like any other.
df = df.withColumn("net", F.col("amount")- F.coalesce(F.col("discount"), F.lit(0)))# Aggregations belong in a window, not a UDF.
w = Window.partitionBy("category")
df = df.withColumn("zscore",(F.col("v")- F.avg("v").over(w))/ F.stddev("v").over(w))# When you genuinely need Python, vectorise it with Arrow. A Series -> Series# pandas_udf is a SCALAR udf: Spark calls it once per Arrow batch, so it must be# element-wise. Anything that reduces across rows (mean, std, rank) would be# computed over one arbitrary batch and be silently wrong.@pandas_udf("double")defhaversine_km(lat: pd.Series, lon: pd.Series)-> pd.Series:return6371.0* np.arccos(
np.clip(np.sin(np.radians(lat))* SIN_REF
+ np.cos(np.radians(lat))* COS_REF * np.cos(np.radians(lon)- LON_REF),-1,1))
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled","true")
Watch out
A row-at-a-time Python UDF is typically 5-20x slower than the equivalent native expression and is opaque to the optimiser: no predicate pushdown, no constant folding, no whole-stage codegen. pandas_udf moves whole Arrow batches instead and closes most of the gap. Mind the type though: a Series -> Series pandas_udf is a scalar UDF called once per batch, so it must be element-wise — put anything that reduces across rows in a window function, or use applyInPandas on a grouped frame, which does see a whole group but will OOM if one group exceeds executor memory.
A TaskFlow DAG with defaults that survive production
The @dag / @task skeleton with catchup, max_active_runs, retries and an execution timeout already set.
AirflowPython
from datetime import datetime, timedelta
from airflow.decorators import dag, task
@dag(
dag_id="orders_daily",
schedule="0 2 * * *",
start_date=datetime(2026,1,1),
catchup=False,# do not launch a year of runs on unpause
max_active_runs=1,# this DAG writes to one table
default_args={"owner":"data-platform","retries":3,"retry_delay":timedelta(minutes=5),"retry_exponential_backoff":True,"execution_timeout":timedelta(hours=2),},
tags=["orders","daily"],)deforders_daily():@taskdefextract(logical_date=None)->str:returnf"s3://lake/raw/orders/dt={logical_date:%Y-%m-%d}/"@taskdeftransform(path:str)->int:
rows =0...return rows
@taskdefpublish(rows:int)->None:print("published", rows)publish(transform(extract()))orders_daily()
Watch out
catchup=False is the setting that stops a DAG with a start_date a year in the past from launching 365 runs the moment somebody unpauses it. execution_timeout is the one people forget: without it a hung task holds a worker slot forever and the run never fails loudly. Anything a @task returns goes through XCom, which is a row in the metadata database — return a path or a row count, never a DataFrame. Context values such as logical_date are injected by parameter name.
Dynamic task mapping: fan out one task per input
expand() creates task instances at run time from a list produced by an upstream task, with the concurrency capped.
AirflowPython
from airflow.decorators import task
@taskdeflist_tables()->list[str]:return["orders","customers","payments","shipments"]@task(max_active_tis_per_dag=4)# cap the width of the fan-outdefingest(table:str, dry_run:bool)->str:returnf"s3://lake/raw/{table}/"@taskdefregister(paths:list[str])->None:print(len(paths),"paths registered")# Constants go through .partial(), the varying argument through .expand().register(ingest.partial(dry_run=False).expand(table=list_tables()))
Watch out
The mapped list is resolved at run time, so the number of task instances can change between runs and the UI collapses them into a single row. Keep the fan-out bounded: a list_tables() that unexpectedly returns 5,000 items creates 5,000 task instances and floods the scheduler and the metadata database. max_active_tis_per_dag, a pool, or both, is the seatbelt. Requires Airflow 2.3 or newer.
Wait for a file without holding a worker slot
S3KeySensor in reschedule mode with a real timeout — the difference between waiting and deadlocking the pool.
AirflowPython
from datetime import timedelta
from airflow.providers.amazon.aws.sensors.s3 import S3KeySensor
wait_for_extract =S3KeySensor(
task_id="wait_for_extract",
bucket_name="lake",
bucket_key="raw/orders/dt={{ ds }}/_SUCCESS",
aws_conn_id="aws_default",
mode="reschedule",# release the worker slot between pokes
poke_interval=timedelta(minutes=5).total_seconds(),
timeout=timedelta(hours=4).total_seconds(),
soft_fail=False,# True -> skip downstream instead of failing)
Watch out
The default mode='poke' holds a worker slot for the entire wait, so a handful of six-hour sensors will deadlock a small cluster while doing nothing at all. reschedule releases the slot between pokes; the cost is that poke_interval becomes a floor rather than a guarantee, and each poke is a fresh task instance in the log. Always set timeout — a sensor without one waits forever and the run silently never finishes. On Airflow 2.6+ prefer deferrable=True where the provider supports it: it uses no slot at all.
Backfill a date range, or re-run one task and everything after it
The two Airflow CLI commands worth memorising, plus how to avoid stampeding the cluster during a backfill.
AirflowBash
# Re-run a closed date range on purpose. --reset-dagruns wipes the existing# runs first, so this is a true replay rather than a no-op.airflow dags backfill orders_daily \
--start-date2026-08-01--end-date2026-08-14 \
--reset-dagruns--yes# Only the failed tasks from an earlier attempt:airflow dags backfill orders_daily \
--start-date2026-08-01--end-date2026-08-14 \
--rerun-failed-tasks--yes# Clear one task and everything downstream of it, for one logical date.airflow tasks clear orders_daily \
--task-regex'^transform$'--downstream \
--start-date2026-08-05--end-date2026-08-05--yes# Sanity-check a schedule without running anything.airflow dags next-execution orders_daily
airflow tasks test orders_daily transform 2026-08-05
Watch out
Set max_active_runs on the DAG before backfilling anything: without it a fourteen-day backfill starts fourteen concurrent runs, and if they all write to the same table you get a race rather than a replay. airflow tasks test runs a single task in the foreground with no scheduler and no database state, which makes it the fastest way to debug an operator. These are the Airflow 2.x flags; Airflow 3 moved backfills into a separate airflow backfill command group with --from-date / --to-date, so check --help before pasting on a 3.x install.
Custom operator skeleton with templated fields
The BaseOperator subclass shape: template_fields, a deferred import inside execute, and an XCom return.
AirflowPython
from typing importAny,Sequencefrom airflow.models import BaseOperator
from airflow.utils.context import Context
classRedshiftUnloadOperator(BaseOperator):"""UNLOAD a query to S3 and return the manifest path through XCom."""# Anything listed here is Jinja-rendered before execute() runs.
template_fields:Sequence[str]=("sql","s3_prefix")
template_ext:Sequence[str]=(".sql",)def__init__(self,*,
sql:str,
s3_prefix:str,
conn_id:str="redshift_default",**kwargs:Any,)->None:super().__init__(**kwargs)self.sql = sql
self.s3_prefix = s3_prefix
self.conn_id = conn_id
defexecute(self, context: Context)->str:# Imported here, not at module scope: the scheduler re-parses every DAG# file on a loop and a slow top-level import slows the whole scheduler.from airflow.providers.amazon.aws.hooks.redshift_sql import RedshiftSQLHook
hook =RedshiftSQLHook(redshift_conn_id=self.conn_id)
inner =self.sql.replace("'","''")
hook.run(f"UNLOAD ('{inner}') TO '{self.s3_prefix}' ""IAM_ROLE default FORMAT AS PARQUET MANIFEST ALLOWOVERWRITE")returnf"{self.s3_prefix}manifest"
Watch out
Fields not listed in template_fields are used literally, which is the number one custom-operator bug: s3_prefix='s3://lake/unload/{{ ds }}/' silently writes a directory with braces in its name. template_ext lets you pass a .sql file path and have Airflow load and render the file for you. Whatever execute() returns is pushed to XCom automatically, so keep it small.
Depend on a task in another DAG
ExternalTaskSensor with execution_delta and failed_states, so a failed upstream fails you instead of hanging.
AirflowPython
from datetime import timedelta
from airflow.sensors.external_task import ExternalTaskSensor
wait_for_dims =ExternalTaskSensor(
task_id="wait_for_dims",
external_dag_id="dimensions_daily",
external_task_id="publish",# None -> wait for the whole DAG run
allowed_states=["success"],
failed_states=["failed","skipped"],# otherwise a failure just hangs
execution_delta=timedelta(hours=1),# upstream 01:00, this DAG 02:00
mode="reschedule",
poke_interval=120,
timeout=3*60*60,)
Watch out
execution_delta is subtracted from this DAG's logical date to find the upstream run, so getting the sign backwards means waiting forever on a run that will never exist. When the two schedules do not differ by a constant, use execution_date_fn instead. Without failed_states a failed upstream leaves the sensor poking until timeout, which turns a five-minute incident into a four-hour one. If both DAGs are yours, an Airflow 2.4+ Dataset or a TriggerDagRunOperator is usually cleaner than a cross-DAG sensor.
Keep the latest row per key with ROW_NUMBER
The dedupe every warehouse needs: rank versions of a row, keep rank 1, and pick the survivor deliberately.
SQLSQL
WITH ranked AS(SELECT*,ROW_NUMBER()OVER(PARTITIONBY order_id
ORDERBY updated_at DESC, ingest_seq DESC)AS rn
FROM staging.orders_raw
WHERE dt =DATE'2026-08-27')SELECT*FROM ranked
WHERE rn =1;-- Snowflake, Databricks and Teradata collapse the CTE into one clause:-- SELECT * FROM staging.orders_raw-- WHERE dt = DATE '2026-08-27'-- QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id-- ORDER BY updated_at DESC, ingest_seq DESC) = 1;
Watch out
SELECT DISTINCT collapses fully identical rows; this collapses versions of a row and lets you choose which one survives. Add a deterministic tiebreaker after the timestamp — an ingest sequence, a Kafka offset, a file name — or the result changes between runs and nobody can reproduce yesterday's numbers. If you only need to detect duplicates rather than remove them, COUNT(*) OVER (PARTITION BY order_id) > 1 is cheaper to read in a review.
Running totals, moving averages and gaps between rows
One query showing SUM, AVG, LAG and NTILE over named windows, with the ROWS-vs-RANGE trap spelled out.
SQLSQL
SELECT
customer_id,
order_date,
amount,SUM(amount)OVER w_running AS ltv_to_date,AVG(amount)OVER(PARTITIONBY customer_id ORDERBY order_date
ROWSBETWEEN6PRECEDINGANDCURRENTROW)AS avg_last_7,LAG(order_date)OVER w AS prev_order_date,
order_date -LAG(order_date)OVER w AS days_between,NTILE(10)OVER(ORDERBY amount DESC)AS spend_decile
FROM analytics.orders
WINDOW
w AS(PARTITIONBY customer_id ORDERBY order_date),
w_running AS(PARTITIONBY customer_id ORDERBY order_date
ROWSBETWEENUNBOUNDEDPRECEDINGANDCURRENTROW)ORDERBY customer_id, order_date;
Watch out
ROWS counts physical rows, RANGE counts logical values — with ties, RANGE pulls in every peer row, and that single difference is behind most 'my running total is wrong' bugs. When you write ORDER BY inside OVER and no frame, the default is RANGE UNBOUNDED PRECEDING, not ROWS. The named WINDOW clause works on Postgres, Trino/Athena and MySQL 8; Redshift and older engines need the full OVER (...) spelled out on every column.
Gaps and islands: collapse consecutive rows into ranges
Turn a per-day activity log into contiguous streaks using the date-minus-row_number trick.
SQLSQL
WITH d AS(SELECTDISTINCT user_id, activity_date
FROM analytics.user_activity
),
grouped AS(SELECT
user_id,
activity_date,-- Constant for any run of consecutive dates.
activity_date -(ROW_NUMBER()OVER(PARTITIONBY user_id
ORDERBY activity_date))::intAS grp
FROM d
)SELECT
user_id,MIN(activity_date)AS streak_start,MAX(activity_date)AS streak_end,COUNT(*)AS streak_days
FROM grouped
GROUPBY user_id, grp
HAVINGCOUNT(*)>=3ORDERBY user_id, streak_start;
Watch out
The trick only works because date minus row_number is constant across a run of consecutive dates — which means the dates must be unique inside each partition, hence the DISTINCT. For timestamps or a non-daily grain, use the LAG plus running-SUM form instead (flag every row that starts a new island, then SUM the flags). Beware of gaps you created yourself by filtering rows out earlier in the query: the streaks will look longer than they are.
Idempotent MERGE into a warehouse dimension
Deduplicate the source inside the USING clause, then merge only when the incoming row is genuinely newer.
SQLSQL
MERGEINTO analytics.dim_customer AS t
USING(SELECT customer_id, name, email, country, updated_at
FROM(SELECT*,ROW_NUMBER()OVER(PARTITIONBY customer_id
ORDERBY updated_at DESC)AS rn
FROM staging.customer_cdc
WHERE updated_at >=DATE'2026-08-27') x
WHERE rn =1)AS s
ON t.customer_id = s.customer_id
WHENMATCHEDAND s.updated_at > t.updated_at THENUPDATESET
name = s.name,
email = s.email,
country = s.country,
updated_at = s.updated_at
WHENNOTMATCHEDTHENINSERT(customer_id, name, email, country, updated_at)VALUES(s.customer_id, s.name, s.email, s.country, s.updated_at);
Watch out
The inner ROW_NUMBER is not decoration: if the source holds two rows for one key the MERGE is non-deterministic — Delta and Snowflake raise a cardinality error, Redshift quietly picks one. The extra AND s.updated_at > t.updated_at is what makes replaying the same batch a no-op, which is exactly what you want when a task retries. MERGE arrived in Redshift in 2023; on older clusters do DELETE-then-INSERT inside a single transaction instead.
Postgres upsert that skips no-op writes
INSERT ... ON CONFLICT DO UPDATE with a WHERE guard, so unchanged rows do not churn the table.
EXCLUDED is the row that would have been inserted. The WHERE on the DO UPDATE skips writes that would change nothing, which keeps updated_at honest and stops the table filling with dead tuples that autovacuum then has to clean up. Use IS DISTINCT FROM rather than <>: with a NULL on either side, <> returns NULL and the guard silently blocks every update. The conflict target needs a real unique index, not just a unique-looking column.
Redshift housekeeping: find what needs VACUUM and ANALYZE
Query svv_table_info first, then vacuum and analyze only the tables that will actually benefit.
SQLSQL
-- 1. Which tables actually need attention?SELECT"table", size AS mb, unsorted, stats_off, tbl_rows, vacuum_sort_benefit
FROM svv_table_info
WHERE unsorted >10OR stats_off >10ORDERBY vacuum_sort_benefit DESC, size DESC;-- 2. Cheap: reclaim space from deleted rows, do not re-sort.VACUUMDELETEONLY analytics.fact_orders;-- 3. Expensive: also re-sort, stopping once the table is 95% sorted.VACUUMFULL analytics.fact_orders TO 95PERCENT;-- 4. Refresh planner statistics after a large load.ANALYZE analytics.fact_orders PREDICATECOLUMNS;-- 5. Did it work?SELECT*FROM svv_vacuum_summary ORDERBY1DESCLIMIT20;
Watch out
stats_off above roughly 10 means the planner is working from stale row counts and will choose bad join orders — that is usually the real cause of a query that 'suddenly got slow', not the data volume. VACUUM FULL can run for hours on a large table and competes with queries for the same resources, so keep it in a maintenance window. ANALYZE PREDICATE COLUMNS only touches columns used in filters, joins and group-bys, which is far cheaper than a full ANALYZE. Modern RA3 clusters auto-vacuum most of this; check before adding your own cron.
Redshift table DDL: distribution, sort keys and encodings
The four decisions that determine whether a Redshift table is fast: diststyle, distkey, sortkey and column encoding.
SQLSQL
CREATETABLE analytics.fact_orders(
order_id VARCHAR(36)NOTNULLENCODEZSTD,
customer_id VARCHAR(36)NOTNULLENCODEZSTD,
order_ts TIMESTAMPNOTNULLENCODERAW,-- leading sort key
status VARCHAR(24)NOTNULLENCODEBYTEDICT,
amount DECIMAL(18,2)NOTNULLENCODEAZ64,PRIMARYKEY(order_id))DISTSTYLEKEYDISTKEY(customer_id)-- same key as analytics.dim_customerCOMPOUNDSORTKEY(order_ts, status);-- Confirm the join is co-located and not redistributing:EXPLAINSELECT f.status,COUNT(*)FROM analytics.fact_orders f
JOIN analytics.dim_customer d ON d.customer_id = f.customer_id
GROUPBY1;-- look for DS_DIST_NONE, not DS_BCAST_INNER / DS_DIST_BOTH
Watch out
Redshift does not enforce PRIMARY KEY — it is a hint the planner trusts, so a duplicate you insert can silently produce wrong results in queries that rely on uniqueness. Give the fact and its dimension the same DISTKEY so the join is DS_DIST_NONE. Put the column you filter on by range first in the SORTKEY: that is what enables zone-map pruning, and it is worth more than any encoding choice. Leave the leading sort key column ENCODE RAW so the block min/max values stay usable.
Athena CTAS: turn raw JSON into partitioned Parquet
The one statement that makes an Athena table 10-100x cheaper to query, and the two rules that break it.
SQLSQL
CREATETABLE curated.orders_2026_08
WITH(format='PARQUET',
parquet_compression ='SNAPPY',
external_location ='s3://lake/curated/orders_2026_08/',
partitioned_by =ARRAY['event_date'],
bucketed_by =ARRAY['customer_id'],
bucket_count =32)ASSELECT
order_id,
customer_id,
amount,
status,
event_date -- partition columns MUST be last, in this orderFROMraw.orders
WHERE event_date BETWEENDATE'2026-08-01'ANDDATE'2026-08-31';
Watch out
Two rules break this silently. First, the partition columns must be the last columns in the SELECT list and in the same order as partitioned_by, otherwise the values land in the wrong partitions with no error. Second, Athena CTAS writes at most 100 partitions per statement — past that you get HIVE_TOO_MANY_OPEN_PARTITIONS and have to loop with INSERT INTO. external_location must be an empty prefix. Athena bills by bytes scanned, so this statement is usually the single biggest cost win available on a raw table.
Sessionize an event stream with a 30-minute inactivity gap
Flag every row that starts a new session, then a running SUM over those flags numbers the sessions.
SQLSQL
WITH tagged AS(SELECT
user_id,
event_ts,
event_name,CASEWHENLAG(event_ts)OVER(PARTITIONBY user_id ORDERBY event_ts)ISNULLOR event_ts -LAG(event_ts)OVER(PARTITIONBY user_id ORDERBY event_ts)>INTERVAL'30 minutes'THEN1ELSE0ENDAS is_new_session
FROM analytics.events
WHERE event_date BETWEENDATE'2026-08-26'ANDDATE'2026-08-27'),
sessions AS(SELECT
tagged.*,SUM(is_new_session)OVER(PARTITIONBY user_id ORDERBY event_ts
ROWSUNBOUNDEDPRECEDING)AS session_num
FROM tagged
)SELECT
user_id,
session_num,MIN(event_ts)AS session_start,MAX(event_ts)AS session_end,MAX(event_ts)-MIN(event_ts)AS duration,COUNT(*)AS events
FROM sessions
GROUPBY user_id, session_num
ORDERBY user_id, session_start;
Watch out
ROWS UNBOUNDED PRECEDING is essential here: with the default RANGE frame, two events sharing a timestamp are folded into the same running total and session numbers drift apart from the flags. Sessions that cross midnight need the previous day in the input, which is why the WHERE spans two dates — filter down to the day you want after the sessions are built, not before. On a very active user this window becomes one large task, so partition the source table by date and keep the range tight.
S3 sync patterns that will not surprise you on the bill
Whitelisting with exclude/include, server-side bucket-to-bucket copies, and why --dryrun is not optional.
AWSBash
# Whitelist idiom: exclude everything, then include what you meant.aws s3 sync ./out s3://lake/curated/orders/ \
--exclude"*"--include"*.parquet" \
--storage-class INTELLIGENT_TIERING \
--only-show-errors# Bucket to bucket, server side. No bytes travel through your laptop.aws s3 sync s3://lake-prod/curated/orders/ s3://lake-dr/curated/orders/ \
--source-region ap-south-1 --region ap-southeast-1
# Before anything with --delete. Every time.aws s3 sync ./out s3://lake/curated/orders/--delete--dryrun# Pulling down: compare exact timestamps, not just size + newer-than.aws s3 sync s3://lake/curated/orders/ ./local/--exact-timestamps
Watch out
--exclude and --include are evaluated in order, which is why the exclude-everything-then-include idiom works. --delete will cheerfully empty a prefix if you point it at the wrong local directory, and S3 has no undo unless versioning was already on. sync compares size and modification time rather than checksums, so a file rewritten to the same size with an older timestamp is skipped entirely — use --exact-timestamps when pulling down. Cross-region sync bills data transfer plus one request per object, so a million tiny files costs far more in requests than the bytes suggest.
Run an Athena query from Python and read the results
start_query_execution plus a backing-off poll loop and a paginated result read, without the throttling.
AWSPython
import time
import boto3
athena = boto3.client("athena", region_name="ap-south-1")defrun(sql:str, database:str, output:str, workgroup:str="primary")->str:
qid = athena.start_query_execution(
QueryString=sql,
QueryExecutionContext={"Database": database},
ResultConfiguration={"OutputLocation": output},
WorkGroup=workgroup,)["QueryExecutionId"]
delay =0.5whileTrue:
status = athena.get_query_execution(
QueryExecutionId=qid
)["QueryExecution"]["Status"]if status["State"]in("SUCCEEDED","FAILED","CANCELLED"):break
time.sleep(delay)
delay =min(delay *2,10)# back off instead of hammering the APIif status["State"]!="SUCCEEDED":raiseRuntimeError(status.get("StateChangeReason","Athena query failed"))return qid
qid =run("SELECT status, COUNT(*) AS n FROM curated.orders ""WHERE event_date = DATE '2026-08-27' GROUP BY 1",
database="curated",
output="s3://athena-results/adhoc/",)
pages = athena.get_paginator("get_query_results").paginate(QueryExecutionId=qid)
rows =[[c.get("VarCharValue")for c in r["Data"]]for page in pages
for r in page["ResultSet"]["Rows"]]print(rows[0],len(rows)-1,"data rows")# rows[0] is the header
Watch out
get_query_execution is throttled per account: a tight poll loop across several concurrent DAG tasks will start returning ThrottlingException, hence the exponential backoff. Athena bills per byte scanned, not per query, so put a per-query data-scanned limit on the workgroup — that one setting is what stops an accidental SELECT * over a year of raw JSON costing hundreds of dollars. For anything large, read the CSV that Athena already wrote to OutputLocation instead of paginating results over the API. Only a SELECT returns a header row.
Trigger a Glue crawler and wait for it properly
Start a crawler, tolerate the already-running case, and fail on the crawl result rather than on the state alone.
AWSPython
import time
import boto3
glue = boto3.client("glue", region_name="ap-south-1")defcrawl(name:str, timeout_s:int=1800)->str:try:
glue.start_crawler(Name=name)except glue.exceptions.CrawlerRunningException:pass# already running: just wait
deadline = time.time()+ timeout_s
while time.time()< deadline:
crawler = glue.get_crawler(Name=name)["Crawler"]if crawler["State"]=="READY":
last = crawler.get("LastCrawl",{})if last.get("Status")!="SUCCEEDED":raiseRuntimeError(f"crawler {name}: "f"{last.get('ErrorMessage', last.get('Status'))}")return last.get("MessagePrefix","ok")
time.sleep(15)raiseTimeoutError(f"crawler {name} did not finish within {timeout_s}s")
Watch out
State == READY only means the crawler stopped; you have to look at LastCrawl.Status to know whether it worked. If your partition layout is predictable (dt=YYYY-MM-DD), skip the crawler entirely: ALTER TABLE ADD PARTITION, MSCK REPAIR TABLE, or Athena partition projection are all faster and cheaper than re-listing a bucket with millions of objects. Crawlers also like to change a column's type when one file disagrees — set the schema change policy to LOG rather than UPDATE_IN_DATABASE for any table with something downstream of it.
Assume a cross-account role and page through S3
An STS session with adaptive retries, plus the list_objects_v2 paginator idiom that survives empty prefixes.
AWSPython
import boto3
from botocore.config import Config
defassume(role_arn:str, session_name:str, region:str="ap-south-1"):
creds = boto3.client("sts").assume_role(
RoleArn=role_arn,
RoleSessionName=session_name,
DurationSeconds=3600,)["Credentials"]return boto3.Session(
aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"],
aws_session_token=creds["SessionToken"],
region_name=region,)
cfg =Config(
retries={"max_attempts":10,"mode":"adaptive"},
max_pool_connections=50,)
session =assume("arn:aws:iam::111122223333:role/DataPlatformReader","airflow-orders")
s3 = session.client("s3", config=cfg)
total = objects =0for page in s3.get_paginator("list_objects_v2").paginate(
Bucket="lake", Prefix="curated/orders/"):
contents = page.get("Contents",[])# absent entirely on an empty page
objects +=len(contents)
total +=sum(o["Size"]for o in contents)print(f"{objects} objects, {total / 1e9:.2f} GB, avg {total / max(objects, 1) / 1e6:.1f} MB")
Watch out
These credentials expire. DurationSeconds cannot exceed the role's maximum session duration, and a long Spark job that assumed a role at startup will start failing halfway through when they lapse — use an instance or task role, or refreshable credentials, for anything long-lived. retries mode 'adaptive' adds client-side rate limiting, which is what keeps a wide list fan-out from tripping S3 503 SlowDown. That average object size at the end is the number worth watching: under a few MB and you have a small-file problem.
Submit a Spark step to EMR and wait for it
The JSON step form (readable, quoting-proof) with the spark-submit tuning flags that actually matter.
ActionOnFailure=CONTINUE keeps the cluster alive so you can read the logs; use TERMINATE_CLUSTER on a transient cluster you are paying for by the second. Around five cores per executor is the usual sweet spot — beyond that HDFS and S3 throughput per executor stops improving — and you must leave roughly 7% of container memory plus a core per node for YARN overhead, so 18g executors on an r5.4xlarge means fewer executors per node than the arithmetic suggests. aws emr wait step-complete gives up after a fixed number of polls (about 30 minutes on current CLI versions), so wrap it in a loop for longer jobs.
Measure what an S3 prefix actually costs you
Object count, total bytes and average object size — the three numbers that reveal a small-file problem.
AWSBash
# Quick and dirty, but it is a paid LIST per 1,000 keys.aws s3 ls s3://lake/curated/orders/--recursive--summarize--human-readable|tail-3# Free, and good enough for tracking growth: CloudWatch daily storage metrics.aws cloudwatch get-metric-statistics \
--namespace AWS/S3 --metric-name BucketSizeBytes \
--dimensions Name=BucketName,Value=lake Name=StorageType,Value=StandardStorage \
--start-time"$(date -u -d '2 days ago' +%Y-%m-%dT00:00:00Z)" \
--end-time"$(date -u +%Y-%m-%dT00:00:00Z)" \
--period86400--statistics Average --output table
# The small-file tax: count, total bytes, and the average object size.aws s3api list-objects-v2 --bucket lake --prefix curated/orders/ \
--query'[length(Contents), sum(Contents[].Size), avg(Contents[].Size)]' \
--output text
Watch out
The CLI auto-paginates list-objects-v2 and applies --query to the merged result, so the last command walks every key under the prefix: fine for thousands, slow and billable for millions. If the average object size comes back under a few MB, a compaction job is almost certainly the cheapest performance win available — Spark spends more time listing and scheduling than reading. date -u -d is GNU; on macOS use date -u -v-2d instead.
Multi-stage image for a Python data job
Build wheels in one stage, ship a venv in a slim runtime, run as a non-root user, keep the layer cache useful.
DockerDockerfile
# ---------- build ----------FROMpython:3.11-slim AS build
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1RUNapt-getupdate \
&&apt-getinstall-y--no-install-recommends build-essential gcc \
&&rm-rf/var/lib/apt/lists/*WORKDIR/app
# Dependencies first, on their own layer: source changes must not reinstall them.COPY requirements.txt .
RUNpython-mvenv/opt/venv \
&&/opt/venv/bin/pipinstall--require-hashes-r requirements.txt
# ---------- runtime ----------FROMpython:3.11-slim AS runtime
ENV PATH="/opt/venv/bin:$PATH" \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1COPY--from=build /opt/venv/opt/venvWORKDIR/app
COPY src/ ./src/RUNuseradd--create-home--uid10001 app &&chown-R app:app /app
USER app
ENTRYPOINT["python","-m","src.job"]
Watch out
Copying requirements.txt on its own before the source is the whole point: put COPY src/ last, or every one-line code change reinstalls the world. The compiler toolchain stays in the build stage, so the final image ships the wheels without gcc — smaller, and a smaller attack surface. PYTHONUNBUFFERED=1 is not optional in a container: without it your logs only appear when the process exits, which is precisely when you no longer need them. --require-hashes needs a fully pinned requirements file; drop it if you are not generating one with pip-compile.
Local Postgres + MinIO stack for pipeline tests
A compose file whose job container actually waits for Postgres to accept connections, not just to start.
DockerYAML
services:postgres:image: postgres:16-alpine
environment:POSTGRES_USER: dev
POSTGRES_PASSWORD: dev
POSTGRES_DB: catalog
ports:["5432:5432"]volumes:- pgdata:/var/lib/postgresql/data
healthcheck:test:["CMD-SHELL","pg_isready -U dev -d catalog"]interval: 5s
timeout: 3s
retries:10minio:image: minio/minio:latest
command: server /data --console-address ":9001"environment:MINIO_ROOT_USER: minio
MINIO_ROOT_PASSWORD: minio12345
ports:["9000:9000","9001:9001"]volumes:- miniodata:/data
job:build: .
depends_on:postgres:condition: service_healthy
environment:PGHOST: postgres
PGUSER: dev
AWS_ENDPOINT_URL: http://minio:9000AWS_ACCESS_KEY_ID: minio
AWS_SECRET_ACCESS_KEY: minio12345
AWS_DEFAULT_REGION: us-east-1
volumes:pgdata:miniodata:
Watch out
depends_on on its own only waits for the container to start, not for Postgres to accept connections — the healthcheck plus condition: service_healthy is what makes the job wait, and skipping it is why local test suites are flaky. Inside the compose network, services reach each other by service name on the container port (postgres:5432), never through the published host port. MinIO speaks the S3 API, so AWS_ENDPOINT_URL is usually all boto3 needs; Spark's S3A connector additionally wants fs.s3a.path.style.access=true.
Run a one-off job container without leaving root-owned files behind
Read-only credential mounts, a UID that matches yours, and hard memory limits on a throwaway container.
Mount credentials read-only and never bake them into the image: an ENV AWS_SECRET_ACCESS_KEY sits in the image history forever, readable by anyone who can pull it. --user with your own uid/gid stops the container writing root-owned files into the mounted data directory, which is the usual reason a later rm -rf needs sudo. --memory matters more than it looks: without a limit a runaway job can take the whole machine down, and with one an over-large Spark driver gets OOM-killed early and visibly instead of slowly swapping.
Reclaim Docker disk, and work out why a container died
Targeted prunes with until filters, plus the inspect field that answers most exit-code-137 questions.
DockerBash
# What is actually using the disk?docker system df -v|head-30# Targeted reclaim. Safer habit than a blanket 'prune -a'.docker container prune -fdocker builder prune -f--filter'until=168h'docker image prune -a-f--filter'until=72h'# Why did it exit? Exit code plus the one field people forget to check.docker logs --tail200 orders-job
docker inspect -f'{{.State.ExitCode}} oom={{.State.OOMKilled}}' orders-job
# A shell inside a running container, even one with no shell of its own.dockerexec-it orders-job /bin/sh
docker run --rm-it--pid container:orders-job \
--network container:orders-job nicolaka/netshoot
Watch out
docker system prune -a deletes every image you are not currently running, including base images you will pull again five minutes later — the --filter until= variants are the habit worth building instead. OOMKilled: true is the answer to most 'my container died with exit code 137' questions; raise the limit or fix the job, do not paper over it with retries. --pid container: gives the debug container the target's process namespace, which is how you strace or inspect a distroless image that ships no shell at all.
The header every pipeline script should start with
set -Eeuo pipefail, a safe IFS, a temp directory that always gets cleaned up, and an ERR trap that names the line.
BashBash
#!/usr/bin/env bashset-Eeuo pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
TMP_DIR="$(mktemp -d)"readonly SCRIPT_DIR TMP_DIR
cleanup(){rm-rf--"$TMP_DIR";}trap cleanup EXIT
trap'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR
log(){printf'%s [%s] %s\n'"$(date -u +%FT%TZ)""$1""${*:2}">&2;}
log INFO "starting in $SCRIPT_DIR"
Watch out
-e exits on error, -u on an unset variable (the thing that turns rm -rf $DIR/ into rm -rf /), -o pipefail makes a failing command anywhere in a pipeline fail the pipeline, and -E is what keeps the ERR trap alive inside functions and subshells. set -e has real blind spots: it does not fire inside if, while, && or || conditions, and local x=$(false) succeeds because the exit status belongs to local, not to the command substitution — declare and assign on separate lines when the status matters.
Run N jobs in parallel and still notice the failures
xargs -P with NUL-delimited input, and a pure-bash bounded pool when you need per-job exit codes.
BashBash
# One partition per job, 8 at a time.aws s3 ls s3://lake/raw/orders/|awk'{print $2}' \
|xargs-P8-I{} bash -c'set -euo pipefail; ./compact.sh "$1"' _ {}# NUL-delimited, so filenames with spaces do not get split in half.find ./data -name'*.json'-print0 \
|xargs-0-r-P"$(nproc)"-n20gzip-9# Bounded pool in pure bash, keeping every job's exit code.# wait -n returns the status of the job it reaps AND removes it from the job# table, so collecting statuses afterwards with 'wait $pid' would report# "not a child of this shell" (127) for jobs that actually succeeded.# Take the status at reap time instead.
failed=0
running=0for dt in2026-08-{01..14};do
./backfill.sh "$dt"&
running=$(( running + 1 ))if(( running >=4));thenwait-n|| failed=1
running=$(( running - 1 ))fidonewhile(( running >0));dowait-n|| failed=1
running=$(( running - 1 ))done
exit "$failed"
Watch out
xargs -I{} implies one argument per command, so pairing it with -n is pointless — drop -I{} when you actually want batching. Always use -print0 with find and -0 with xargs: a single filename containing a space is otherwise split into two arguments and you silently process the wrong thing. -r stops xargs running the command at all on empty input, which is what prevents a stray rm from running with no arguments. The bounded pool needs Bash 4.3+ for wait -n; the system bash on macOS is 3.2, so use the xargs -P form there or install a newer bash.
Retry a flaky command with exponential backoff
A reusable retry function that preserves quoting, returns the real exit code, and only wraps idempotent work.
BashBash
retry(){local max="${1:-5}" delay="${2:-2}"shift2local attempt=1 code=0until"$@";do
code=$?if(( attempt >= max ));thenecho"giving up after $attempt attempts (exit $code): $*">&2return"$code"fi# Jitter, so a hundred workers do not all come back at the same instant.local sleep_for=$(( delay + RANDOM % delay ))echo"attempt $attempt failed (exit $code); retrying in ${sleep_for}s">&2sleep"$sleep_for"
delay=$(( delay * 2 ))
attempt=$(( attempt + 1 ))done}
retry 52aws s3 cp ./out.parquet s3://lake/curated/orders/out.parquet
retry 81curl-fsS--max-time30 https://api.internal/health
Watch out
Running "$@" directly keeps the caller's quoting intact; building a command string and eval-ing it is how retry helpers grow injection bugs. Only retry things that are genuinely idempotent — retrying aws s3 cp is safe, retrying a non-idempotent POST is how you charge somebody twice. curl in particular needs -f or it exits 0 on an HTTP 500 and your retry loop never fires; --max-time stops a hung connection from consuming the entire retry budget in one attempt.
Delete old files safely, on disk and in S3
Preview with -printf before you delete, batch through xargs -0, and filter an S3 listing by date.
BashBash
# 1. Preview. Always look at the list before deleting it.find/var/log/pipelines -type f -name'*.log'-mtime+14 \
-printf'%TY-%Tm-%Td %10s %p\n'|sort# 2. Delete, batching arguments instead of forking rm per file.find/var/log/pipelines -type f -name'*.log'-mtime+14-print0 \
|xargs-0-rrm-f--# 3. Empty directories, deepest first.find/var/log/pipelines -type d -empty-delete# 4. Same idea in S3: the CLI has no mtime filter, so filter the listing.aws s3 ls s3://lake/tmp/--recursive \
|awk-v cutoff="$(date -u -d '30 days ago' +%F)"'$1 < cutoff { print $4 }' \
|xargs-r-I{}aws s3 rm"s3://lake/{}"
Watch out
-mtime +14 means strictly more than 14 whole 24-hour periods ago, which is why -mtime +0 is not 'today' and off-by-one deletions are so common. find -delete has no dry run and no undo, so run the preview first, every time. -r on xargs is what stops an empty listing turning into a command with no arguments. Step 4 is better solved with an S3 lifecycle rule, which is free and runs without you; use the CLI version only for one-off cleanups. -printf and date -d are GNU — on macOS use date -v-30d and stat -f.
jq recipes for AWS output and NDJSON
TSV extraction, safe defaults for missing keys, streaming aggregation, and the only safe in-place edit idiom.
BashBash
# Nested list to TSV, ready for cut/awk/sort.aws emr list-clusters --active \
|jq-r'.Clusters[] | [.Id, .Name, .Status.State] | @tsv'# Filter, then reshape into a smaller object.jq-r'.[] | select(.status == "FAILED") | {id, task: .task_id, msg: .error}' runs.json
# Safe defaults, so one missing key does not kill the whole pipeline.jq-r'.Contents[]? | "\(.Key)\t\(.Size // 0)"' listing.json
# Aggregate NDJSON. -s slurps into memory; inputs streams.jq-s'map(.bytes_scanned) | add' queries.ndjson
jq-n'[inputs.bytes_scanned] | add' queries.ndjson
# Edit a config in place. jq cannot do this itself.
tmp=$(mktemp) \
&&jq'.retries = 5 | .owner = "data-platform"' conf.json >"$tmp" \
&&mv"$tmp" conf.json
Watch out
-r prints raw strings instead of JSON-quoted ones; without it every field arrives wrapped in double quotes and the awk downstream of it quietly breaks. The ? after an iterator suppresses the error when a key is missing, which is exactly what list-objects-v2 returns for an empty prefix. jq -s reads the entire input into memory, so use jq -n with inputs for files bigger than RAM. jq never edits in place — redirecting straight back into the source file truncates it before jq has read it, so the mktemp-and-mv dance is not optional.
awk one-liners for log and TSV triage
Group-and-sum, percentile, status counts and duplicate keys, without loading anything into a dataframe.
BashBash
# GROUP BY col 1, SUM col 3, COUNT rows. The poor man's aggregate.awk-F'\t''{ s[$1] += $3; n[$1]++ }
END { for (k in s) printf "%s\t%d\t%.2f\n", k, n[k], s[k] }' events.tsv \
|sort-k3-nr|head-20# p95 of the last column, no dataframe required (gawk).awk'{ a[NR] = $NF } END { n = asort(a); print "p95 =", a[int(n * 0.95)] }' latency.log
# Count HTTP statuses in an access log, most common first.awk'{ c[$9]++ } END { for (s in c) print c[s], s }' access.log |sort-nr# Print each duplicated key exactly once: the fastest MERGE post-mortem there is.awk-F'\t''seen[$1]++ == 1 { print $1 }' keys.tsv
Watch out
asort is gawk-only; on the BSD awk that ships with macOS, pipe through sort -n and pick the row by line number instead. awk -F, is not a CSV parser — one quoted comma inside a field shifts every column after it, so only use it on TSV or on CSV you generated yourself. $NF is the last field, which is what makes the p95 one-liner survive logs with a variable number of leading columns. seen[$1]++ == 1 prints a duplicate once rather than once per extra copy.
Where these came from
Nearly five years of this was built on Nykaa's data platform — an in-house ingestion framework, a Dataplatform Catalog API holding the metadata, and a generator that turned that catalog into Airflow DAGs at runtime, all sitting on Spark, EMR, Databricks, Redshift and S3. The rest comes from tuning Spark cost and performance, processing e-commerce cart CDC, comparing Hudi against Delta and Iceberg, and now multi-cloud and cost work at Ninja Van. These are the fragments that survived being rewritten a few times.
The pattern I keep hitting is that the code is the easy half. Anybody can write a MERGE. What costs you a weekend is knowing that it becomes non-deterministic the moment the source holds two rows for one key, that mode("overwrite") deletes an entire partitioned table unlesspartitionOverwriteMode is set to dynamic, that an Airflow sensor in the default poke mode occupies a worker slot for six hours while doing nothing, and that Athena CTAS writes values into the wrong partitions without an error if the partition columns are not last in the SELECT. That is what the caveat under each snippet is for, and it is why some of them are longer than the code above them.
What is deliberately missing
No framework of the month, nothing I have only read about, and nothing that needs a dependency you would not already have. Where a snippet is engine-specific — Redshift's svv_table_info, the 100-partition limit on Athena CTAS, gawk's asort — the caveat says so, because the fastest way to lose an afternoon is to paste Postgres syntax into Redshift and read the error as a logic bug.
Using the page
Search covers titles, tags, the caveats and the code itself; every term you type has to match.
Category and language filters are independent — Airflow plus Bash gives you the backfill CLI, not the DAG code.
Filters live in the URL fragment, so a filtered view is a link you can send.
Press / to jump to the search box; Link on any snippet copies its permalink.
Everything runs in your browser. No account, no server, and the page keeps working offline.
Frequently asked questions
Can I copy these into work code?
Yes. They are here to be pasted. None of them are secret, none of them contain anything specific to an employer, and the point of the page is that you do not have to reconstruct them from a half-remembered Stack Overflow answer at 2am.
Which versions do these target?
Spark 3.x, Airflow 2.x, Delta Lake 2.x and up, AWS CLI v2 and boto3, Postgres 14+ and Redshift RA3. Anywhere a snippet depends on a specific version or engine — Airflow 3 renaming the backfill flags, MERGE only landing in Redshift in 2023, gawk-only asort — the caveat underneath says so.
Why is the caveat sometimes longer than the code?
Because the code is the easy half. A MERGE statement is ten lines anybody can write; knowing that it is non-deterministic when the source has two rows for one key is the part that costs you a production incident. The caveat is the reason the snippet is worth keeping.
Can I link to one snippet, or to a filtered view?
Both. The Link button on any snippet copies a permalink such as /snippets#s=pyspark-skew-salting. Filters live in the URL too, so /snippets#cat=airflow or /snippets#q=window&lang=sql is a link you can send to a colleague and it opens in the same state.
Does the search look inside the code?
Yes — titles, descriptions, tags, the caveats and the full source are all indexed, and every term you type has to match. Searching row_number returns the SQL dedupe, the PySpark dedupe and the sessionization query together. Press / anywhere on the page to jump to the search box.