Overview and What You Will Learn
Amazon Athena runs standard SQL directly on files in S3, and AWS Glue prepares that data and keeps its schema in a shared catalog. Together with Lake Formation for access control, they make a serverless analytics stack with no clusters to run. In the lab you query a CSV in place, convert it to partitioned Parquet, and compare how much data each query scans.
By the end you will be able to:
- Explain how Athena reads data in place and how it is billed
- Cut scan cost with columnar formats, compression, partitioning and larger files
- Use partition projection and Athena CTAS for fast conversions
- Describe Glue ETL, the Data Catalog, crawlers, job bookmarks, DataBrew and streaming ETL
- Use Athena Federated Query to join S3 with other data sources
- Explain what Lake Formation adds: central row-level and column-level permissions
- Trace a full serverless pipeline from IoT device to dashboard
Why This Matters in Production
A food delivery company such as Swiggy produces millions of order and delivery events a day. Keeping all of it in a relational database for analytics is expensive, while keeping it as files in S3 and querying it with Athena costs a fraction as much and scales without capacity planning. A payments company such as Razorpay can run exploratory queries on raw logs in Athena, load curated data into a warehouse, and use Glue pipelines to turn raw files into query-ready Parquet.
The hard part is cost and discipline. Athena bills for data scanned, so the same question can cost ten times more on CSV than on partitioned Parquet. Knowing the handful of habits below is what separates a cheap, fast pipeline from an expensive one.
Core Principles
What Is Amazon Athena and How Is It Billed?
Athena is a serverless query service that runs SQL on data stored in S3, with nothing to provision and no data to load. It reads CSV, JSON, Parquet, ORC and Avro files, and its engine is based on Trino and Presto. In many Regions you pay about $5 per TB of data scanned, with a minimum charge per query, so check your Region's pricing. Failed queries and DDL statements are not billed for scanning.
RememberAthena never moves data. Every optimisation exists to reduce the bytes a query must read, which lowers both cost and run time.
- Good fits: ALB, CloudTrail and VPC Flow Log analysis, AWS Cost and Usage Report queries, ad-hoc exploration, data lake queries
- Poor fits: high-concurrency application backends and low-latency transactions
Why Does Parquet Make Athena Cheaper?
Parquet and ORC are columnar formats that store each column together, so a query reads only the columns it needs. Row-based CSV or JSON must be read in full even when you want one column. Columnar files are also compressed and carry statistics that let Athena skip data, which commonly cuts scanned bytes by 30 to 90 percent.
Query: SELECT AVG(amount) FROM orders CSV reads every column of every rowParquet reads only the amount column| Format | Athena suitability |
|---|---|
| CSV and JSON | Works, but scans everything |
| Avro | Better than CSV, still row based |
| Parquet and ORC | Recommended, columnar |
How Do You Make Athena Queries Faster and Cheaper?
Apply four habits in order: use a columnar format, compress, partition, and keep files large. The first gives the biggest win, and the others multiply it.
- Columnar format: Convert to Parquet or ORC.
- Compression: Snappy balances speed and size, and zstd and gzip compress more. Parquet supports compression inside the file.
- Partitioning: Lay out S3 paths so filters can skip whole folders.
- File size: Aim for files of at least 128 MB, because thousands of tiny files add per-file overhead.
Unpartitioned: s3://logs/app.log.2024.01.15 (query scans everything)Partitioned: s3://logs/year=2024/month=01/day=15/part-0.parquetFilter: WHERE year = '2024' AND month = '01' AND day = '15'TipAlways filter on partition columns in the WHERE clause. A query without a partition filter still scans every partition.
How Do You Register Partitions in Athena?
Athena must know which partitions exist before it can use them. You can run MSCK REPAIR TABLE, add partitions with ALTER TABLE ADD PARTITION, let a Glue crawler find them, or use partition projection. Projection computes partition locations from table properties instead of reading the catalog, so there is nothing to keep updated and it stays fast with many partitions.
CREATE EXTERNAL TABLE devops_analytics.app_logs ( request_id string, status int)PARTITIONED BY (year string, month string, day string)STORED AS PARQUETLOCATION 's3://devops-logs-rahul/app/'TBLPROPERTIES ( 'projection.enabled' = 'true', 'projection.year.type' = 'integer', 'projection.year.range' = '2024,2030', 'projection.month.type' = 'integer', 'projection.month.range' = '1,12', 'projection.month.digits' = '2', 'projection.day.type' = 'integer', 'projection.day.range' = '1,31', 'projection.day.digits' = '2', 'storage.location.template' = 's3://devops-logs-rahul/app/year=${year}/month=${month}/day=${day}/');What Is Athena CTAS and When Should You Use It Instead of Glue?
CTAS (CREATE TABLE AS SELECT) writes the result of a query as a new table in a format and layout you choose, so it converts CSV to partitioned, compressed Parquet with one SQL statement. For simple one-off or SQL-only conversions, CTAS is often faster to build than a Glue job. Use Glue when you need Spark logic, many sources, scheduling and bookmarks, or complex transforms.
What Is Athena Federated Query?
Federated Query lets one Athena SQL statement read from sources beyond S3 through Lambda-based data source connectors. Connectors exist for sources such as DynamoDB, RDS and Aurora, DocumentDB, Redis, CloudWatch, and JDBC databases. Use it for occasional joins across systems, and not as a replacement for loading data you query constantly.
SELECT o.order_id, u.emailFROM s3_logs.orders oJOIN rds_prod.users u ON o.user_id = u.id;What Is AWS Glue?
Glue is a serverless data integration service whose ETL jobs run on Apache Spark, with Python shell and visual authoring options too. ETL means extract, transform, load: read from a source, clean or convert the data, and write it to a destination. You pay for the compute (DPUs) while a job runs, and there are no servers to manage.
The most common Glue pattern is turning raw CSV or JSON into Parquet:
import sysfrom awsglue.utils import getResolvedOptionsfrom pyspark.context import SparkContextfrom awsglue.context import GlueContextfrom awsglue.job import Job args = getResolvedOptions(sys.argv, ['JOB_NAME'])glue_context = GlueContext(SparkContext())job = Job(glue_context)job.init(args['JOB_NAME'], args) source = glue_context.create_dynamic_frame.from_catalog( database='devops_raw', table_name='orders_csv', transformation_ctx='source',) # Write Parquet to the curated bucketglue_context.write_dynamic_frame.from_options( frame=source, connection_type='s3', connection_options=dict(path='s3://devops-analytics/orders_parquet/'), format='parquet', transformation_ctx='sink',) job.commit()What Are the Glue Data Catalog and Crawlers?
The Data Catalog is a central metadata store of databases, tables, columns, types and S3 locations, shared by Athena, Glue, EMR, Redshift Spectrum and Lake Formation. A crawler scans a data source, infers its schema and partitions, and creates or updates tables in the catalog. With scheduled crawlers, schema changes appear automatically instead of requiring hand-written CREATE TABLE statements.
aws glue create-crawler \ --name devops-orders-crawler \ --role arn:aws:iam::123456789012:role/GlueRole \ --database-name devops_analytics \ --targets 'S3Targets=[{Path=s3://devops-raw-data/orders/}]' \ --schedule "cron(0 1 * * ? *)" \ --region ap-south-1 aws glue start-crawler --name devops-orders-crawler --region ap-south-1aws glue get-crawler --name devops-orders-crawler \ --query 'Crawler.State' --output text --region ap-south-1TipPoint each crawler at a prefix that holds one table's data in one format. Mixed formats under one path create confusing tables.
What Do Glue Job Bookmarks, DataBrew and Streaming ETL Do?
Bookmarks make a job process only new data, DataBrew cleans data without code, and streaming ETL transforms data continuously.
- Job bookmarks: Track what a job has already processed so each run handles only new data. Pass
transformation_ctxin the script, as shown above, so bookmarks work. - DataBrew: A visual tool with more than 250 transformations for removing duplicates, fixing formats, filling gaps and masking PII, saved as recipes you can schedule.
- Streaming ETL: Spark Structured Streaming jobs that read from Kinesis Data Streams, Kafka or MSK and write continuously to S3 or other targets.
aws glue create-job \ --name devops-orders-etl \ --role arn:aws:iam::123456789012:role/GlueRole \ --command Name=glueetl,ScriptLocation=s3://devops-scripts/etl.py \ --default-arguments '--job-bookmark-option=job-bookmark-enable' \ --region ap-south-1What Is AWS Lake Formation?
Lake Formation builds and governs a data lake on S3 and the Glue Data Catalog, and its main value is central, fine-grained access control. You grant permissions on databases, tables, columns and rows once, and they are enforced for integrated engines such as Athena, Redshift Spectrum, EMR, Glue and QuickSight. Without it you maintain separate IAM and S3 policies per service and per team.
- Column-level security: The finance team sees the salary column and others do not
- Row-level security: A regional analyst sees only rows where region is ap-south-1, using data filters
- LF-tags: Tag-based access control that scales across many tables
A data lake stores any data type and applies schema on read, while a warehouse such as Redshift needs structured data loaded with a schema defined first. Many teams use both.
RememberLake Formation sits on top of Glue and the Data Catalog. Use Glue alone for ETL, and add Lake Formation when several teams need different views of the same data. Make sure Lake Formation, not legacy IAM-only access, is the permission model for the databases you govern.
What Does a Serverless Big Data Pipeline Look Like?
A common serverless pipeline moves data from devices to dashboards with no servers to run. Devices send events to IoT Core, Kinesis Data Streams collects them with replay, and Amazon Data Firehose batches them into S3 and can convert JSON to Parquet on the way. A Glue crawler keeps the catalog current, Athena queries the data, and QuickSight builds dashboards. Redshift Serverless handles heavy BI queries that need a warehouse.
Detailed Step-by-Step Practical Lab
This lab queries a small CSV, then converts it to partitioned Parquet with Athena CTAS and compares scanned bytes. Replace rahul with your own suffix, since bucket names are global. Athena bills a minimum per query, so tiny files will show similar costs. The value of the lab is the workflow.
Step 1: Create buckets and the sample data
export AWS_REGION=ap-south-1 aws s3 mb s3://devops-athena-results-rahulaws s3 mb s3://devops-raw-orders-rahulaws s3 mb s3://devops-curated-orders-rahul cat > orders.csv <<'EOF'order_id,user_id,amount,city,statusORD-001,user-101,450.00,Mumbai,deliveredORD-002,user-102,1200.00,Pune,pendingORD-003,user-101,89.00,Mumbai,deliveredORD-004,user-103,2500.00,Bangalore,deliveredORD-005,user-102,340.00,Pune,cancelledEOF aws s3 cp orders.csv s3://devops-raw-orders-rahul/orders/orders.csvIn the Athena console, open Settings and set the query result location to s3://devops-athena-results-rahul/.
Step 2: Create the database and a CSV table
CREATE DATABASE devops_analytics; CREATE EXTERNAL TABLE devops_analytics.orders ( order_id string, user_id string, amount double, city string, status string)ROW FORMAT DELIMITEDFIELDS TERMINATED BY ','STORED AS TEXTFILELOCATION 's3://devops-raw-orders-rahul/orders/'TBLPROPERTIES ('skip.header.line.count'='1');Step 3: Run queries and read Data scanned
SELECT city, COUNT(*) AS orders, SUM(amount) AS revenueFROM devops_analytics.ordersGROUP BY cityORDER BY revenue DESC; SELECT * FROM devops_analytics.orders WHERE status = 'delivered';After each query, note the Data scanned figure below the results. That is what you pay for.
Step 4: Convert to partitioned Parquet with CTAS
CREATE TABLE devops_analytics.orders_parquetWITH ( format = 'PARQUET', write_compression = 'SNAPPY', external_location = 's3://devops-curated-orders-rahul/orders_parquet/', partitioned_by = ARRAY['city']) ASSELECT order_id, user_id, amount, status, cityFROM devops_analytics.orders;The partition column must be last in the SELECT list, and the external location must be empty. Run the revenue query against orders_parquet and compare Data scanned. A query that filters on city now reads only that folder.
Step 5: Create a Glue crawler
In AWS Glue, create a crawler named devops-orders-crawler with the S3 source s3://devops-raw-orders-rahul/orders/, a new IAM role, the target database devops_analytics, and an on-demand schedule. Run it. When it succeeds, a table appears in the catalog with a detected schema that Athena can query straight away.
Step 6: Clean up
DROP TABLE devops_analytics.orders;DROP TABLE devops_analytics.orders_parquet;DROP DATABASE devops_analytics;aws glue delete-crawler --name devops-orders-crawleraws s3 rb s3://devops-athena-results-rahul --forceaws s3 rb s3://devops-raw-orders-rahul --forceaws s3 rb s3://devops-curated-orders-rahul --forceProduction Best Practices & Common Pitfalls
- Use Parquet or ORC before scaling Athena: It is the biggest single saving.
- Partition from the start: Re-partitioning later means rewriting the data.
- Use partition projection for time-based layouts: It avoids partition maintenance.
- Keep files large: Compact small files to 128 MB or more.
- Use workgroups: Set per-workgroup result locations and a data scanned limit per query to stop runaway cost.
- Keep results separate: Use a dedicated bucket for query results, never the source bucket.
- Schedule crawlers, or manage tables as code: New data and schema changes stay visible.
- Enable job bookmarks for incremental ETL: Avoid reprocessing history.
- Use Lake Formation for multi-team access: Define row and column rules once.
- Select only the columns you need: Avoid SELECT star on wide tables.
Common MistakeRunning Athena on large CSV files in production. A query that needs one column still scans every column, so it costs far more than the same query on Parquet.
Common MistakeWriting partitioned paths but never registering the partitions. The table returns no rows. Use partition projection, a crawler, or MSCK REPAIR TABLE.
TipTo debug a slow or costly query, run EXPLAIN. Usual causes are no partition filter, a non-columnar format, and too many small files.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| List Glue databases | aws glue get-databases --region ap-south-1 |
| List tables | aws glue get-tables --database-name <db> --region ap-south-1 |
| Start a crawler | aws glue start-crawler --name <name> --region ap-south-1 |
| Start a Glue job | aws glue start-job-run --job-name <name> --region ap-south-1 |
| List job runs | aws glue get-job-runs --job-name <name> --region ap-south-1 |
| Run an Athena query | aws athena start-query-execution --query-string "SELECT 1" --result-configuration OutputLocation=s3://<bucket>/ |
| Get query results | aws athena get-query-results --query-execution-id <id> |
| Problem | Likely cause and fix |
|---|---|
| Query scans too much data | CSV, no partition filter, or wide SELECT. Convert to Parquet and filter on partitions. |
| No rows after adding files | Partitions not registered. Use MSCK REPAIR TABLE, ADD PARTITION, a crawler or projection. |
| Header row appears as data | Missing skip.header.line.count property on the CSV table. |
| Crawler misses schema changes | Crawler not rerun. Run it or shorten its schedule. |
| Glue job reprocesses everything | Bookmarks off or no transformation_ctx. Enable both. |
| Access denied through Lake Formation | Missing Lake Formation grant for the principal on the table or columns. |
| Many tiny files slow queries | Compact into larger files with CTAS or a Glue job. |