serverless cloud · Freelance

Build an S3 Data Lake with Glue Crawlers, ETL Jobs and Athena SQL

A queryable S3 data lake: raw CSVs land in a bucket, Glue crawlers infer schemas, an ETL job writes partitioned Parquet, and Athena answers SQL questions over it.

  • Amazon S3
  • AWS Glue
  • Glue Data Catalog
  • Amazon Athena
  • Parquet
  • PySpark
  • IAM
  • Elasticsearch

// Why this matters

An s3 data lake with glue and athena is the lowest-friction way to turn a pile of files into something people can query with SQL. Teams routinely end up with exports, logs and CSV dumps that nobody can analyse without importing them into a database first, which means a pipeline, a schema decision and a server before the first question is answered.

The serverless lake inverts that order. You land data first and impose structure later. The catalog gives every dataset a table name, and Athena bills per terabyte scanned, so an unused lake costs only storage. That is a strong fit for analytics projects where demand is unpredictable.

I have built this for flight-delay style analytics and for log and social-media analysis, where raw volumes were large and the questions kept changing. The same layout worked for both.

// The problem

Raw CSV is the worst format for analytics at volume. Athena has to read every byte of every row even when the query touches two columns, and string-typed columns defeat predicate pushdown. Queries that look cheap, such as a filter on one airport code, scan the whole dataset and are billed accordingly.

Schemas also drift. A producer adds a column, renames one, or changes a numeric field to contain the text NA, and downstream reports break at three in the morning. Hand-written CREATE TABLE statements go stale the moment a new file shape appears.

Finally there is the governance gap. Without separate zones, raw files, cleaned data and query output share one prefix, so nobody can say what is safe to delete, what is authoritative, and which files an analyst may read.

// The solution

The design uses one bucket with three prefixes: raw/ for immutable landed files, curated/ for Parquet that the ETL job produces, and athena-results/ for query output. Each prefix gets its own lifecycle rule. Raw is kept, curated is rebuildable, and results expire after a few weeks.

A Glue crawler points at raw/ and writes a table into a Glue database. It samples files, infers column names and types, and detects partition folders. Running it on a schedule (or after each landing) registers new files and surfaces drift as a changed table version. Crawlers are convenient but they guess, so once a schema is stable I pin the types in the ETL job with an explicit mapping.

The ETL job is a Glue PySpark script. It reads the raw table as a dynamic frame, applies the type mapping, drops the rows that fail a basic quality check, and writes Parquet partitioned by a date column. Parquet is columnar and compressed, so Athena reads only the needed columns, and partition pruning skips whole folders.

Athena queries run in a dedicated workgroup. The workgroup fixes the results location and sets a per-query bytes-scanned cutoff, so one careless SELECT star cannot burn the budget. For the log and social-media workloads I added a second consumer on the same raw data: a Lambda that indexes documents into Elasticsearch for text search, while Athena handles aggregate analysis. Two engines, one source of truth.

Rejected alternatives: loading into Redshift (cluster cost and ingestion pipeline for exploratory work), and querying CSV directly forever (cheap to start, expensive at scale). A related serverless ingestion pattern is in Presigned-Upload Document Parsing API.

How it flows flow1. Land raw files → 2. Crawl → 3. Transform → 4. Partition → 5. Catalog → 6. Quality gate → 7. Query → 8. Share01Land raw files02Crawl03Transform04Partition05Catalog06 · GATEQuality gate07Query08Share
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Land raw filesCSV drops arrive under raw/ in the lake bucket
  2. Crawla Glue crawler infers columns and registers a raw table
  3. Transforma Glue ETL job reads the table and writes Parquet
  4. Partitionoutput is partitioned by date and written under curated/
  5. Cataloga second crawler or the job itself registers the curated table
  6. Quality gate gaterow counts and null checks compared before promoting
  7. QueryAthena runs SQL through a workgroup with a scan limit
  8. Shareresults land in a results bucket for BI tools or export
ConsumersAthena SQLBI dashboardsElasticsearch searchCatalogGlue databaseraw tablecurated tableProcessingGlue crawlerGlue ETL jobQuality checksStorageraw/ CSVcurated/ Parquetathena-results/
Lake zones and services. Each zone has a purpose, an owner and a lifecycle.
ProducerS3GlueCatalogAthenaput raw/day=.../file.csvcrawler samples filescreate or update raw tableETL writes curated parquetregister curated partitionsresolve table + partitionsscan only needed columns
From landed file to answer. What runs, in order, when a new file arrives.

// Before you start

  • An AWS account with permissions for S3, Glue, Athena and IAM role creation
  • AWS CLI v2 configured for <region>
  • A sample dataset of CSV files with a header row (flights, logs or orders all work)
  • Basic SQL; familiarity with Spark helps but is not required
  • An S3 bucket name that is globally unique, referred to here as <lake-bucket>

// Step-by-step implementation

  1. 01 Create the bucket zones and lifecycle

    One bucket, three prefixes. Create them by uploading empty marker objects or just by writing into them. The lifecycle rule on the results prefix keeps Athena output from accumulating forever.

    Enable default encryption and block public access; data lakes are a classic source of accidental exposure.

  2. 02 Give Glue an IAM role

    Glue assumes a role to read the raw zone and write the curated zone. Attach the managed Glue service policy, then add a scoped inline policy for the lake bucket rather than broad S3 access.

    Keeping read-only on raw/ and write on curated/ means a buggy job can never damage the source files.

  3. 03 Crawl the raw data into the Glue Data Catalog

    Create a database and a crawler targeting the raw prefix. The crawler needs the role, the database name and a schedule or on-demand trigger. After it runs, you will have a table whose columns match the CSV header.

    Check the inferred types. Columns with sporadic text values are inferred as strings, and that is a signal to fix them in the ETL step.

  4. 04 Write the ETL job: CSV to partitioned Parquet

    The job reads the cataloged table, casts columns explicitly, filters obviously broken rows, and writes Parquet partitioned by month. Explicit casting is what protects downstream queries from drift.

    Partition on a column that queries filter by and that has moderate cardinality. A date part is the usual choice; a high-cardinality key creates millions of tiny files.

  5. 05 Register and run the curated table

    Upload the script, create the job with the role, and run it. Then point a second crawler at curated/ so the Parquet table and its month partitions are registered. Alternatively run MSCK REPAIR TABLE from Athena after you create the table by hand.

    From now on analysts should use the curated table, and the raw table is for reprocessing only.

  6. 06 Create an Athena workgroup with a scan limit

    The workgroup enforces the results location and a per-query data limit. Set the limit low at first; you can raise it deliberately. Also publish query metrics to CloudWatch so you can chart scanned bytes.

    Enforcing the workgroup configuration means individual users cannot override the output path.

  7. 07 Answer a real question with a self-join

    A good test of the lake is a question that needs two scans of one table: find one-stop itineraries from an origin to a destination through a connecting airport on the same airline. It is a self-join, and it shows partition pruning and column pruning paying off.

    Select only the columns you need and filter early inside each subquery, so each side scans a small slice.

// How to verify it works

  • aws glue get-tables lists both a raw and a curated table, and the curated table shows month as a partition key.
  • SHOW PARTITIONS flight_data.flights in Athena returns one row per month written by the job.
  • The same filtered query on the raw CSV table reports far more data scanned than on the curated table (compare Data scanned in the console).
  • A deliberately huge query is cancelled by the workgroup cutoff instead of completing.
  • Result files appear under athena-results/ and disappear after the lifecycle expiry.

// Design decisions and trade-offs

  • Separate raw, curated and query-results prefixes so each zone has a clear contract
  • Convert CSV to partitioned Parquet in a Glue ETL job to cut Athena scan cost
  • Let crawlers own schema discovery, but pin table definitions once they stabilise
  • Use a dedicated Athena workgroup with a scan limit and its own results bucket
  • Keep ingestion into Elasticsearch as a separate branch for log and social analytics

// Pitfalls and lessons learned

  • Crawlers merge schemas across files; one file with an extra header row can turn a numeric column into a string for the whole table.
  • Athena cannot read a prefix that mixes formats. Keep one format per table prefix.
  • Forgetting to register new partitions makes recent data invisible. Re-run the crawler or use partition projection.
  • Writing many small files (over-partitioning) makes queries slower and costlier; coalesce before writing.
  • Overwriting the curated prefix while an Athena query is reading it can return partial results; write to a new prefix and swap the table location when it matters.
  • Glue job role without s3:ListBucket on the bucket gives confusing access denied errors for existing prefixes.

// Frequently asked questions

How do I build an s3 data lake with glue and athena?

Land files in S3, crawl them into the Glue Data Catalog, convert to partitioned Parquet with a Glue job, and query the tables from Athena through a workgroup.

Why convert CSV to Parquet?

Parquet is columnar and compressed, so Athena reads only the columns and partitions a query needs, which lowers both cost and latency.

Do I always need a crawler?

No. Crawlers are convenient for discovery; for stable datasets you can create tables by hand or use partition projection and skip the crawl.

How do I control Athena cost?

Use a workgroup with a bytes-scanned cutoff, partition your data, store Parquet, and select only needed columns.

Where does Elasticsearch fit?

Use it for full-text search over logs or posts; keep Athena for aggregate SQL. Both can read from the same raw data.

// The outcome

Analysts can run ad hoc SQL over raw files without loading a database, and the curated Parquet zone keeps query cost proportional to the columns and partitions actually read. Schema drift is detected by the crawler rather than discovered by a failed report.

// Where to take it next

  • Add partition projection so new days appear without any crawler run.
  • Trigger the ETL job from S3 events or a schedule using Glue workflows.
  • Add Lake Formation permissions for column-level access control.
  • Apply the same layout to audit data, as in Automated IAM Compromise Detection and Credential Revocation.