June 11, 2026

Tuning AWS Glue PySpark Jobs for Speed and Cost

AWS Glue is easy to start with: write a PySpark script, choose a worker type, click run. It's also easy to overpay for. Most Glue jobs I've reviewed were either over-provisioned "just in case" or spent most of their time on problems that more workers can't fix: small files, reading partitions they didn't need, or skewed joins.

Delegated authority data hits all three. The bordereaux themselves are processed by the bordereaux platform. Downstream, the data team receives the platform's output (its reporting layer, or a regular feed of risk, premium and claims transactions) and builds data products on top. Those feeds arrive as many small incremental files. Getting the latest position of each risk tempts jobs to re-read years of history. And a handful of large binders account for most of the premium. This is the checklist I use when a Glue job is slow, expensive, or both.

Understand the bill first

Glue Spark jobs are billed per DPU-hour, per second, with a 1-minute minimum on current Glue versions. Worker types map to DPUs:

WorkerDPUvCPU / memoryTypical use
G.1X14 vCPU / 16 GBMost ETL; the sensible default
G.2X28 vCPU / 32 GBMemory-heavy joins, wide aggregations
G.4X / G.8X4 / 816-32 vCPU / 64-128 GBVery large shuffles; rarely needed

So 10 × G.2X for one hour is 20 DPU-hours, the same as 20 × G.1X. The question is never "how big?" on its own. It's "how big, for how long?"

1. Use the latest Glue version

Glue 5.0 runs Spark 3.5 with Python 3.11, and each new version has brought real performance improvements from newer Spark (Adaptive Query Execution improvements, faster Parquet reading) and faster start-up. Moving older jobs from Glue 3.0 to a current version often makes them noticeably cheaper, with no code changes beyond fixing deprecated APIs.

2. Turn on auto scaling

1: --enable-auto-scaling  true

With auto scaling on, Number of workers becomes a maximum, and Glue adds or removes executors as the job's stages need them. A typical job on the bordereaux feed has one heavy stage (joining the latest transactions to contract sections and converting currencies) and then a long tail of light work, and auto scaling stops you paying for idle executors during that tail. This is the single easiest saving.

3. Use Flex for anything that isn't urgent

The Flex execution class runs jobs on spare capacity at a significantly lower DPU rate (roughly a third cheaper). The trade-off is that start-up can be delayed and runs aren't guaranteed to start immediately.

1: aws glue start-job-run \
2:   --job-name claims_history_rebuild \
3:   --execution-class FLEX

Historical rebuilds, reloading full history after the platform redelivers a feed, and test runs are good candidates. The month-end premium and claims loads that underwriters are waiting for aren't. A simple rule is to split jobs into "must finish for the month-end pack" (Standard) and "anytime overnight" (Flex), and often more than half can go on Flex.

4. Read less data: pushdown predicates

The most common waste I find: a job reads an entire Glue Catalog table, every feed delivery since the platform went live, and then filters to the latest delivery in Spark. Push the filter into the read so Glue only lists and reads the partitions you need:

1: feed_date = args["feed_date"]
2: 
3: premium = glueContext.create_dynamic_frame.from_catalog(
4:     database="raw",
5:     table_name="feed_premium",
6:     push_down_predicate=f"feed_date = '{feed_date}'",
7:     additional_options={"catalogPartitionPredicate": f"feed_date = '{feed_date}'"},
8: )

catalogPartitionPredicate filters on the Glue Catalog side using partition indexes. On feed tables partitioned by delivery date, the partition count grows quickly, and this can cut minutes from the job's start before Spark does any real work.

If you use the Spark DataFrame API directly (spark.read.parquet(...) or spark.table(...)), a WHERE on partition columns gives you partition pruning. Just make sure it's applied before any operation that stops Spark pushing it down.

5. Fix small files on the way in

Incremental feeds from the bordereaux platform tend to arrive as many small files: one per entity, per delivery, sometimes per batch. Over a few years that's a lot of small files to list and open. Glue can group them into larger read tasks:

 1: risk_bdx = glueContext.create_dynamic_frame.from_options(
 2:     connection_type="s3",
 3:     connection_options={
 4:         "paths": ["s3://my-data-bucket/feeds/risks/"],
 5:         "recurse": True,
 6:         "groupFiles": "inPartition",
 7:         "groupSize": "134217728",
 8:     },
 9:     format="json",
10: )

6. ...and on the way out

Don't create the next job's small-file problem. Control output file counts:

1: (risk_df.repartition("year_of_account", "bordereau_month")
2:     .write.mode("overwrite")
3:     .partitionBy("year_of_account", "bordereau_month")
4:     .option("maxRecordsPerFile", 5_000_000)
5:     .parquet("s3://my-data-bucket/curated/risks/"))

Better still, write to an Iceberg table, which Glue supports natively (--datalake-formats iceberg), and let compaction (Glue Data Catalog's automatic optimisation or a scheduled rewrite_data_files) handle file sizes over time. Iceberg's MERGE also makes corrected feed deliveries far easier to apply than overwriting partitions.

7. Job bookmarks for incremental processing

For jobs that process "new feed files since last run", Glue job bookmarks track what has been processed:

1: --job-bookmark-option  job-bookmark-enable
1: src = glueContext.create_dynamic_frame.from_catalog(
2:     database="raw", table_name="feed_claims",
3:     transformation_ctx="src_feed_claims",
4: )
5: job.commit()

Two gotchas: forget transformation_ctx and the bookmark silently does nothing; forget job.commit() and every run reprocesses everything. And if the platform redelivers a corrected file under the same name, a bookmark may skip it, so agree versioned file names with the feed owner.

8. Look at the metrics before adding workers

Turn on the Spark UI and continuous logging (--enable-spark-ui true, --spark-event-logs-path s3://...) and Glue job observability metrics. I tune Glue jobs from their CloudWatch metrics first, then the Spark UI. Before scaling up, look for:

  • One task taking much longer than the rest in a stage usually means data skew, often one large binder or facility. More workers won't help. Check AQE skew join handling (spark.sql.adaptive.skewJoin.enabled, on by default), broadcast the smaller side, or salt the hot key.
  • Lots of disk spill points to memory pressure. Moving from G.1X to G.2X with fewer workers can be cheaper than adding more G.1X.
  • Executors idle most of the time means the job is over-provisioned. Lower the max workers or rely on auto scaling.
  • The driver busy while executors wait usually means something is calling collect(), toPandas() or a Python loop over binders on the driver.

9. Broadcast small dimensions

Contract sections, coverholders, brokers and month-end rates of exchange are small next to the transaction facts. Broadcast them:

1: from pyspark.sql.functions import broadcast
2: 
3: premium_enriched = (premium_df
4:     .join(broadcast(dim_section), ["umr", "section_no"], "left")
5:     .join(broadcast(dim_broker), "broker_code", "left")
6:     .join(broadcast(fx_rates), ["original_ccy", "bordereau_month"], "left"))

AQE often does this automatically when it can see the size, but an explicit hint is reliable when the dimension comes from a source Spark can't size well, such as a JDBC read from an in-house SQL Server.

Results

Applying this list (Glue version upgrade, auto scaling, Flex for non-urgent jobs, pushdown predicates, and output compaction) usually saves a lot, and the month-end jobs often finish earlier too. Most of it is just checking the basics, one job at a time.

Do the cheap things first, measure with the Spark UI, and only then pay for more workers.

January 22, 2026

CI/CD for dbt with GitHub Actions: Slim CI and Safe Deployments

Once a dbt project has more than a handful of models and more than one developer, "run it locally and push to main" stops being safe. A change to a staging model can break a mart three levels down, and nobody finds out until the morning run fails or, worse, succeeds with wrong numbers.

This post shows the CI/CD setup I use for dbt with GitHub Actions: build and test only what changed on every pull request, in an isolated schema, and deploy to production on merge. The examples use Databricks, but the workflow is the same for any adapter.

The goals

  • Every pull request is built and tested before it can be merged.
  • CI only builds what changed and what depends on it, not the whole project.
  • CI runs in its own schema, so it never touches production tables.
  • Production deploys happen from main only, never from a laptop.

Slim CI: build only what changed

dbt can compare the current project with the manifest from production (manifest.json, written by every run) and select only modified models:

1: dbt build --select state:modified+ --defer --state ./prod-artifacts
  • state:modified+: models whose SQL or config changed, plus everything downstream of them (the +).
  • --defer: when a selected model refers to a model that wasn't rebuilt, read the production version instead. So CI doesn't need to build the whole upstream graph.
  • --state: where to find the production manifest.

A change to fct_claims builds that model and its downstream marts, reading unchanged dimensions from production. A pull request that touches two models finishes in minutes instead of rebuilding years of transactions.

Isolated schemas for each pull request

Give CI its own target in profiles.yml, with the schema taken from an environment variable:

 1: analytics:
 2:   outputs:
 3:     ci:
 4:       type: databricks
 5:       host: "{{ env_var('DATABRICKS_HOST') }}"
 6:       http_path: "{{ env_var('DATABRICKS_HTTP_PATH') }}"
 7:       token: "{{ env_var('DATABRICKS_TOKEN') }}"
 8:       catalog: ci
 9:       schema: "{{ env_var('DBT_CI_SCHEMA') }}"
10:       threads: 8
11:     prod:
12:       type: databricks
13:       host: "{{ env_var('DATABRICKS_HOST') }}"
14:       http_path: "{{ env_var('DATABRICKS_HTTP_PATH') }}"
15:       token: "{{ env_var('DATABRICKS_TOKEN') }}"
16:       catalog: prod
17:       schema: reporting
18:       threads: 8

Each pull request gets a schema like pr_142 in a separate CI catalog, so two developers' pull requests can't overwrite each other, and none of them can touch production.

Keeping the production manifest

Slim CI needs the latest production manifest.json. The simplest approach is to have the production deploy upload it as a build artifact, or copy it to cloud storage, and have CI download it. I prefer storage, because artifacts expire:

1: aws s3 cp target/manifest.json s3://my-dbt-artifacts/prod/manifest.json

The pull request workflow

 1: # .github/workflows/dbt-ci.yml
 2: name: dbt-ci
 3: on:
 4:   pull_request:
 5:     branches: [main]
 6: 
 7: jobs:
 8:   build-and-test:
 9:     runs-on: ubuntu-latest
10:     env:
11:       DATABRICKS_HOST:      ${{ secrets.DATABRICKS_HOST }}
12:       DATABRICKS_HTTP_PATH: ${{ secrets.DATABRICKS_HTTP_PATH }}
13:       DATABRICKS_TOKEN:     ${{ secrets.DATABRICKS_CI_TOKEN }}
14:       DBT_CI_SCHEMA:        pr_${{ github.event.pull_request.number }}
15:       DBT_PROFILES_DIR:     ./ci
16:     steps:
17:       - uses: actions/checkout@v4
18:       - uses: actions/setup-python@v5
19:         with: { python-version: '3.11' }
20:       - run: pip install dbt-databricks==1.10.*
21:       - run: dbt deps
22: 
23:       - name: Get production manifest
24:         run: |
25:           mkdir -p prod-artifacts
26:           aws s3 cp s3://my-dbt-artifacts/prod/manifest.json prod-artifacts/ || echo "no manifest, full build"
27: 
28:       - name: Lint SQL
29:         run: pip install sqlfluff sqlfluff-templater-dbt && sqlfluff lint models
30: 
31:       - name: Build and test changed models
32:         run: |
33:           if [ -f prod-artifacts/manifest.json ]; then
34:             dbt build --target ci --select state:modified+ --defer --state prod-artifacts
35:           else
36:             dbt build --target ci
37:           fi

(The AWS step needs credentials too. With GitHub's OIDC integration you can assume an IAM role without storing access keys.)

Make the workflow a required status check on the main branch, so a pull request can't be merged until its models build and its tests pass.

The deploy workflow

 1: # .github/workflows/dbt-deploy.yml
 2: name: dbt-deploy
 3: on:
 4:   push:
 5:     branches: [main]
 6: 
 7: jobs:
 8:   deploy:
 9:     runs-on: ubuntu-latest
10:     environment: production
11:     env:
12:       DATABRICKS_HOST:      ${{ secrets.DATABRICKS_HOST }}
13:       DATABRICKS_HTTP_PATH: ${{ secrets.DATABRICKS_HTTP_PATH }}
14:       DATABRICKS_TOKEN:     ${{ secrets.DATABRICKS_PROD_TOKEN }}
15:       DBT_PROFILES_DIR:     ./ci
16:     steps:
17:       - uses: actions/checkout@v4
18:       - uses: actions/setup-python@v5
19:         with: { python-version: '3.11' }
20:       - run: pip install dbt-databricks==1.10.*
21:       - run: dbt deps
22:       - run: dbt build --target prod --exclude test_type:unit
23:       - run: aws s3 cp target/manifest.json s3://my-dbt-artifacts/prod/manifest.json

Unit tests already ran in CI, so production skips them. The GitHub environment adds an approval step, which also gives you an audit trail of who released what and when.

Many teams don't run the whole project on every merge. Instead, the scheduled production job (in Databricks Workflows, Airflow or similar) runs dbt build on its normal timetable, and the merge simply makes the new code available to it. Either works. What matters is that production only ever runs code from main.

Cleaning up

CI schemas pile up. A small workflow on pull_request: closed can drop the schema for that pull request:

1:       - run: dbt run-operation drop_schema

Here drop_schema is a short macro in the project that runs DROP SCHEMA ... CASCADE.

Small habits that help

  • Pin dbt and package versions so CI and production behave the same.
  • Use conventional commits (feat:, fix:) and you can generate release notes and version tags automatically.
  • Use separate tokens or service principals for CI and production, with CI unable to write to production catalogs.
  • Keep CI fast. If a pull request takes more than about ten minutes, people start bypassing it. Slim CI and deferral are what keep it quick.

None of this is specific to insurance, but it matters more when the output feeds Lloyd's returns and finance reconciliations. A tested, reviewed, repeatable release process is much easier to explain to an auditor than "it worked on my machine".