ETL, ELT, batch and streaming: choosing how data moves into your warehouse

TL;DR

Difficulty: Intermediate

Load first, transform in the warehouse (ELT), and keep the raw copy so every wrong rule can be rerun.

  • Transform before loading only for personal data you may not keep, data you must never store, or volume nobody queries.
  • Daily batch, plus hourly where someone acts within the day, is the honest default. Streaming is for jobs that act in seconds.
  • Pull for the truth, push for speed, and let a scheduled pull sweep up what a webhook missed.
  • Talk to APIs with cursors, a rate budget, capped exponential backoff with jitter, and runs that are safe to repeat.

Every source in a shop hands over its data differently: a database, an analytics export, ad platforms, payment APIs, a warehouse partner's CSV. This chapter shows how to choose the order (ETL or ELT), the rhythm (batch or streaming), who moves first (push or pull) and what to build or buy, then walks through an API extractor that survives rate limits, timeouts and reruns.

The question behind this chapter

Wrenfield Home sells homeware online from Leeds. Priya, the owner, wants one morning report she can trust. Callum, her developer and data engineer, already knows where the report should be built: in a cloud warehouse, BigQuery in a European region, with the cleaning layers from the chapter on raw, staging and clean layers.

What he has not decided yet is the plumbing. Orders live in the shop's PostgreSQL database. Sessions live in Google Analytics 4 (GA4). Ad costs live with Google and Meta. Payments live with Stripe and PayPal. Shipments and returns arrive as a semicolon separated file from the third party logistics (3PL) warehouse. Product data comes from supplier feeds. Each source has its own way of handing data over, its own speed and its own ways of failing.

This chapter answers one question: how should data get from those systems into the warehouse? It covers the order of the work (ETL or ELT), the rhythm (batch, micro batch or streaming), who starts the conversation (push or pull), what you build and what you buy, and how to talk to an API so that a bad night does not cost you a day of data. It ends with a decision table for every source of the example shop.

One promise up front: most of the hard problems in data movement are not about speed. They are about what happens when something goes wrong halfway, and whether running the job again makes things better or worse.

Every data movement has three steps: extract, load, transform

Any pipeline that moves data does three things. It extracts the data from the source system, it loads the data into the place where analysis happens, and it transforms the data into the shape the reports need: typed, cleaned, joined and summed.

The three letters in ETL and ELT are exactly these three steps. The only difference between the two words is the order of the last two, and that order decides a great deal: where the cleaning code runs, what you can still recover when a rule turns out to be wrong, and what personal data ends up stored where.

Example: one Stripe payment on its way to the report

A customer in Bristol buys a linen throw for £72 on Tuesday evening. Stripe records a charge, and with it a balance transaction: £72.00 gross, a fee, and the net amount that will reach Wrenfield's bank account.

  1. Extract: on Wednesday at 5am, a small job asks the Stripe API for every balance transaction created since the last run, and receives this one among 54 others.
  2. Load: the job writes the 55 objects, unchanged, into a raw table in BigQuery, each stamped with the batch it came in and the time it was fetched.
  3. Transform: a dbt model reads the raw table, turns the amounts from pence into pounds, converts the Unix time stamp into a proper time stamp, and joins the transaction to the order in the shop database through the payment reference.

The report at 8am shows Tuesday's net revenue, fees included. Three steps, in that order. That order is what the industry now calls ELT.

ETL: transform before you load

For decades the standard order was ETL. Data was extracted from the source systems, transformed on a separate integration server, and only the finished result was loaded into the data warehouse. Ralph Kimball and Joe Caserta's book on the subject, The Data Warehouse ETL Toolkit, published in 2004, is still the classic description of that world, with extraction, cleaning, conforming and delivery as its four stages.1

The reason for the order was cost. Warehouse databases of that era ran on expensive, fixed hardware. Storage was scarce and compute was shared with every report. Loading raw data you might never use, and transforming it inside the warehouse, would have taken capacity away from the people running reports. So the transformation happened outside, and the warehouse received only clean, summarised, conformed tables.

ETL has one serious weakness. Whatever the transformation threw away is gone. If the nightly job summed orders per day before loading, the warehouse never saw a single order. When a new question arrives that needs the detail, you cannot answer it from the warehouse. You go back to the source, if the source still has the data.

Example: the summary that could not answer the next question

Imagine Wrenfield had been built the old way. A nightly ETL job reads the day's orders, removes test orders, sums revenue per product category and loads one row per category per day into the warehouse. Five years of history fit into a small table.

Then Priya asks: "How many of last year's customers bought twice within 90 days?" The warehouse cannot answer. It holds category totals, not customers and not orders. Callum would have to go back to the shop database, which still holds the orders, and build a new extraction for this one question.

Worse, suppose the test order rule was wrong for the first two years and also removed orders from Priya's own staff discount code, which were real sales. In an ETL design the original rows were never stored in the warehouse, so the past cannot be corrected from there. It has to be rebuilt from the source, and only if the source kept the rows.

ELT: load first, transform inside the warehouse

Cloud warehouses changed the arithmetic. In BigQuery, Snowflake and their peers, storage and compute are separate. Storage is billed by the gigabyte and is plentiful. Compute is rented by the query or by the second and scales up for the length of a query and back down afterwards. The research behind BigQuery, Google's Dremel paper from 2010, describes a system that runs aggregation queries over tables with trillions of rows in seconds by combining a columnar data layout with a tree of servers that split the work.2

Once storage is plentiful and compute is elastic, the old reasons for ETL fall away. You can afford to load every row exactly as it arrived, and do the transformation inside the warehouse in SQL, where it is versioned, tested and rerun at will. That is ELT. It is the order behind tools like dbt, and it is what made the raw layer from chapter 15 affordable: the raw copy is the insurance policy for every rule you will ever get wrong.

Tap or click to open full screen and move around

Example: what the raw layer costs Wrenfield

Callum estimates the raw data per year. These are invented but realistic sizes for the example shop:

SourceRows per yearApproximate raw size per year
Orders and line items (spree_orders, spree_line_items)about 23,760 orders, 55,000 line itemsunder 0.1 GB
Stripe balance transactionsabout 19,700under 0.1 GB
GA4 events (daily export)about 23.8 millionabout 40 GB
Google Ads and Meta Ads daily reportsabout 200,000under 1 GB
3PL shipments and returns filesabout 26,000under 0.1 GB

The GA4 line dominates. Google states that 1 GB holds roughly 600,000 GA4 events, depending on event size.3 At 110,000 sessions a month and an assumed 18 events per session, that is 1,980,000 events a month, about 23.8 million a year, or roughly 40 GB.

BigQuery's own price list shows the first 10 GiB of active logical storage free each month, with the price per gibibyte hour beyond that, and it does not charge for batch loading data from Cloud Storage or local files when the shared slot pool is used.4 At these sizes the raw layer costs a few pounds a month. The bill that matters is query cost, which a later chapter on performance and cost covers. For the shop, ELT is not a luxury. It is the less expensive option, because keeping the raw rows costs less than one afternoon of rebuilding a lost history.

When transforming before loading is still right

ELT is the default, not a religion. Three situations still call for a transformation before the data is stored, and they are worth naming because getting them wrong is expensive.

The first is personal data you have no reason to keep. The data minimisation principle in Article 5(1)(c) of the UK GDPR requires personal data to be "adequate, relevant and limited to what is necessary" for the purpose.5 The Information Commission (formerly the Information Commissioner's Office, ICO) explains that you should not hold more than you need for that purpose.6 A raw layer that copies every column of every system "just in case" collides with that principle. The fix is narrow: drop or pseudonymise the specific fields in flight, and load everything else as received. This is general information and not legal advice. A later chapter on privacy engineering covers retention and erasure across raw layers in depth.

The second is data you must never store, such as full card numbers. A shop on Stripe never sees them in the first place, which is the best version of this rule.

The third is sheer volume. If a source produces far more data than any question needs, such as raw server logs at one line per request, filtering before the load saves real money. Some people call the resulting pattern EtLT: a small, mechanical "t" in flight (drop, hash, filter), and the real transformation later in the warehouse.

Example: the customer service export

Wrenfield's customer service tool can export every ticket, including the full text of every message. Callum wants the ticket metadata in the warehouse: created time, category, order reference, first response time, resolution time. He does not need the message bodies, which contain addresses, phone numbers and the occasional photo of a broken lamp.

So the extractor keeps 9 named fields and drops the rest before writing a single byte. The ticket count, categories and response times are all available for analysis. The personal content stays in the tool that was built to hold it. The raw layer still holds exactly what the extractor received for those 9 fields, so every later rule can be rerun.

Batch, micro batch and streaming

The second decision is the rhythm. There are three, and the words are often used loosely, so here they are precisely.

Batch means the data is moved in chunks on a schedule: every night, every hour. Each run handles a bounded set of records, such as "everything created yesterday", and finishes.

Micro batch means the same thing at a very short interval, every few seconds or minutes. Apache Spark's Structured Streaming works this way by default: its documentation describes a micro batch engine that processes a stream as a series of small batch jobs and reaches end to end latencies as low as 100 milliseconds.7

Streaming means each event is processed as it arrives, continuously, with no schedule at all. Tyler Akidau's essay Streaming 101 (O'Reilly, 2015) is the clearest introduction to the idea. He argues that the useful distinction is between bounded data (a finite set) and unbounded data (a set that never ends), and that "streaming" should describe the engine, not the data.8 A batch job run every hour over an unbounded stream of orders is still processing unbounded data, in slices.

The trade is always the same. The shorter the interval, the fresher the data, and the more moving parts there are to run, monitor and pay for. Streaming systems must deal with events that arrive late, out of order or twice, all the time and not just during an incident. A later chapter on streaming in depth covers event time, watermarks and delivery guarantees.

Example: GA4 offers both, and Google recommends the slower one

The GA4 BigQuery export comes in two forms. The daily export writes one complete table per day, named events_YYYYMMDD. The streaming export writes events into a table named events_intraday_YYYYMMDD within a few minutes.3

Google's own page is frank about the trade. It calls the streaming export "a best effort operation" that may not include all data, notes that some data such as user attribution may be delayed by up to 24 hours, and recommends the daily export instead of streaming for that reason. Streaming also costs extra: $0.05 per gigabyte (Google states the price in US dollars).3

For Wrenfield, the money is trivial:

streaming cost=1,980,000600,000×0.05=0.165\text{streaming cost} = \frac{1{,}980{,}000}{600{,}000} \times 0.05 = 0.165

Here 1,980,0001{,}980{,}000 is the monthly event count, 600,000600{,}000 is Google's estimate of events per gigabyte, and 0.050.05 is the price per gigabyte in dollars. The result is about 17 US cents a month. The cost that matters is not the bill. It is that intraday numbers are incomplete, change during the day and disagree with the daily table. Priya makes no decision before 9am that needs GA4 data younger than a day. So Callum uses the daily export and leaves streaming off.

The honest default: daily or hourly batch

Here is the plain recommendation for a business the size of the example shop: move data in batches, once a day, and once an hour for the few sources where someone acts within the day. Streaming earns its place for specific jobs, such as fraud checks during checkout, stock levels shared between channels, or personalisation on the page, and those jobs usually live inside the application, not in the warehouse.

The way to decide is to ask who acts on the number and how fast. Then work out how old the data will be under each schedule.

For a source loaded on a fixed schedule, the age of the newest data at the moment someone looks is, on average and at worst:

Aˉ=I2+R+DAmax⁡=I+R+D\bar{A} = \frac{I}{2} + R + D \qquad A_{\max} = I + R + D

Here Aˉ\bar{A} is the average age of the data when someone looks at a random moment, Amax⁡A_{\max} is the worst case age, II is the interval between runs, RR is how long a run takes, and DD is any delay inside the source before the data is even available. The I2\frac{I}{2} term is there because, looked at a random moment, you are on average halfway through an interval. For the reasoning behind averages like this one, see Foundations: the mean.

Example: how fresh is Wrenfield's order data under each schedule?

Orders come from the shop database, so D=0D = 0. Callum compares four schedules, with run times he measured on a test run.

Daily at 5am, run time 30 minutes:

Aˉ=242+0.5+0=12.5 hours\bar{A} = \frac{24}{2} + 0.5 + 0 = 12.5 \text{ hours}

With I=24I = 24 hours and R=0.5R = 0.5 hours, the worst case Amax⁡A_{\max} is 24.5 hours, just before the next run lands.

Every six hours, run time 15 minutes: Aˉ=3+0.25=3.25\bar{A} = 3 + 0.25 = 3.25 hours. Hourly, run time 10 minutes: Aˉ=0.5+0.17=0.67\bar{A} = 0.5 + 0.17 = 0.67 hours, about 40 minutes. Every 15 minutes, run time 5 minutes: Aˉ=0.125+0.083=0.21\bar{A} = 0.125 + 0.083 = 0.21 hours, about 13 minutes.

Now the other side of the decision. Priya reads the report at 9am and decides on ad budgets weekly. Returns come from the 3PL, whose returns file arrives up to 5 days late, so for returns DD can be 120 hours and no schedule on Callum's side changes that. The only person who acts within the day is the customer service lead, who wants to know about failed payments before lunch.

So Callum runs everything daily at 5am, and one small hourly job for payment failures. Going faster would buy nothing that anyone acts on.

Bars of the average age of the newest order data at a random moment, for four load schedules at the invented example shop, using average age equals half the interval plus run time. Daily at 5am: 12.5 hours. Every six hours: 3.25 hours. Hourly: 0.67 hours. Every 15 minutes: 0.21 hours. The step from daily to hourly removes most of the age, the step to 15 minutes adds little in absolute terms. Tap or click to open full screen and move around

Lambda and kappa: two architectures you will hear about

Two names come up whenever batch and streaming are discussed, and an experienced reader will expect them here.

The Lambda architecture goes back to a blog post by Nathan Marz from 2011. It runs two paths side by side: a batch layer that recomputes complete, correct views from all historical data, and a real time layer that covers only the recent data the batch layer has not processed yet. Queries merge the two.910 It gives you fresh numbers and correct numbers, at the cost of writing and running the same logic twice.

In 2014 Jay Kreps, who was building the real time data infrastructure at LinkedIn on Apache Kafka and Samza, questioned that cost. His alternative, which he half jokingly called the Kappa architecture, keeps a single streaming path and handles reprocessing by replaying the stored log of events through a new version of the same job.10 One code path, at the price of keeping the full event log and running a streaming system all the time.

Example: why Wrenfield runs neither

Callum sketches a Lambda design for live revenue: a streaming path from Stripe events into a live table, and the nightly batch path for the correct numbers. Two code paths would compute "net revenue" and must agree to the penny, and every rule change would need doing twice. The only consumer of a live revenue figure would be Priya refreshing a dashboard during a sale, which changes no decision.

Kappa would need a permanent event log and a stream processor, running every hour of every day, for 66 orders a day. Both patterns solve a real problem that Wrenfield does not have. Callum writes that down, with the date, so that the question gets asked again when the business changes, rather than answered by fashion.

Push or pull: who starts the conversation?

The third decision is who moves first.

In a pull design, your extractor asks the source for data: "give me everything since 5am yesterday". You control the timing, the pace and the retries. If your job fails, the data is still in the source, waiting for the next attempt.

In a push design, the source sends data to you when something happens. Webhooks are the common form: Stripe calls a URL in your application whenever a payment succeeds. Push is fast, and saves you from polling an API that has nothing new to say. It also moves the responsibility. You must be online when the call arrives, answer quickly, and cope with deliveries that come twice or in the wrong order.

Stripe's documentation spells out all three duties. It retries a failed delivery for up to three days with exponential backoff in live mode. It says that endpoints "might occasionally receive the same event more than once" and should log processed event IDs to skip duplicates. It does not guarantee delivery in the order events were generated, and it warns that event creation times are recorded in seconds, so distinct events can share a time stamp and must not be used to decide order.11 The chapter on where raw data comes from draws exactly this case, a webhook delivered twice and out of order.

The most reliable designs use both: push for speed, and a scheduled pull as the sweep that catches whatever the push missed. Push tells you something happened. Pull confirms what is true.

Example: the deploy that swallowed a webhook

Wrenfield's Rails application stores every Stripe webhook in a table before doing anything else, and processes it later in a background job. The controller answers within milliseconds, as Stripe asks.

# app/controllers/stripe_webhooks_controller.rb (Rails 8)
class StripeWebhooksController < ActionController::API
  def create
    event = Stripe::Webhook.construct_event(
      request.raw_post,
      request.headers["Stripe-Signature"],
      Rails.application.credentials.stripe_webhook_secret
    )
    # The unique index on stripe_event_id makes a second delivery a no op.
    StripeEvent.insert_all(
      [{ stripe_event_id: event.id, event_type: event.type,
         payload: event.to_hash, received_at: Time.current }],
      unique_by: :stripe_event_id
    )
    ProcessStripeEventsJob.perform_later
    head :ok
  rescue JSON::ParserError, Stripe::SignatureVerificationError
    head :bad_request
  end
end

construct_event checks the signature against the raw request body, as Stripe's guide shows, so a forged call is rejected.11 The insert_all with unique_by turns a duplicate delivery into nothing, because PostgreSQL refuses the second row with the same event ID. The work happens in a background job, the pattern the article on background workers explains in depth.

On a Thursday, a deploy takes the application down for 40 seconds. Stripe retries the webhooks it could not deliver, and most arrive minutes later. Suppose one does not, because the endpoint was briefly misconfigured after the deploy and Stripe's retries ran out. The nightly pull from the Stripe API at 5am lists every balance transaction created since the last run, finds the payment, and the warehouse is complete anyway. The webhook made the order confirmation fast. The pull made the books right.

Four ways to ingest: native exports, managed connectors, open source and your own code

The fourth decision is what does the moving. There are four families, and a sensible platform usually mixes them.

Native exports come from the source vendor itself. GA4 exports to BigQuery. Google's BigQuery Data Transfer Service loads Google Ads reports daily, and by default reads the last 7 days again on every run (its "refresh window", configurable up to 30 days), so that recent days, whose conversion figures can still change, are refreshed.12 BigQuery can also read a Google Sheet directly as an external table.13 When a native export exists and covers what you need, it is usually the first choice: no code, no server and the vendor maintains it.

Managed connectors are services that run extraction for you, for hundreds of sources, and write into your warehouse. Fivetran is a well known example. Its pricing counts monthly active rows (MAR): every distinct primary key synced in a calendar month counts once, however often it changes.14 On 23 November 2026 its pricing page listed a free plan up to 500,000 MAR for connections, with paid plans above.15 Stitch, which its website describes as a Qlik product, prices by rows per month, with its Standard plan starting at $100 on the same date.16 Plans change often, so check the current page and the vendor's own estimator before you rely on any figure.

Open source tools let you run connectors on your own servers. Airbyte is a prominent example. Its documentation describes a self managed version that is free and open source, and a managed cloud service besides.17 You get the catalogue of connectors without the per row bill, and in exchange you operate the servers, the upgrades and the monitoring.

Your own code is a script or a small service that talks to the API directly. It is the right choice when no connector covers the source well (an unusual 3PL file format, a supplier feed in a shape nobody else uses), when you need exact control over what is kept, or when the volume is so small that a connector's overhead exceeds the code's.

Example: build or buy for the Stripe source

Callum compares a connector with his own extractor for Stripe. The figures for his time are invented for the example.

The monthly cost of owning a custom extractor is:

Cown=Hb hm+Hm h+IC_{\text{own}} = \frac{H_b \, h}{m} + H_m \, h + I

Here CownC_{\text{own}} is the monthly cost of the custom extractor, HbH_b is the hours to build it, hh is the hourly cost of the person who builds and maintains it, mm is the number of months over which the build is spread, HmH_m is the maintenance hours per month, and II is the monthly infrastructure cost. It is a ratio of one off cost to months plus a running cost, see Foundations: ratios and rates.

With Hb=16H_b = 16 hours, h=60h = 60 pounds, m=24m = 24 months, Hm=2H_m = 2 hours and I=5I = 5 pounds:

Cown=16×6024+2×60+5=165C_{\text{own}} = \frac{16 \times 60}{24} + 2 \times 60 + 5 = 165

That is Cown=165C_{\text{own}} = 165 pounds a month, of which 120 is maintenance. Maintenance dominates, which is the usual finding and the one most build decisions forget.

On the other side, Wrenfield's Stripe account produces about 1,640 balance transactions a month. At that volume a connector's free or entry plan may well cover the source. The honest comparison is therefore not money but fit. Does the connector land the fields Callum needs, with the history he needs, in a raw form he can rerun? Can he see what it did when a number looks wrong? For Stripe the answer is yes for most connectors, and buying is the sensible call. For the 3PL's semicolon separated, Windows 1252 encoded file with its own SKU prefix, no connector knows the format, and Callum writes his own.

Working with APIs properly

Most of a data engineer's ingestion code talks to HTTP APIs. An API (application programming interface) is a door into someone else's system with a rulebook attached. The rulebook says how to ask for data in pages, how fast you may ask, what happens when you ask too fast, and how the answer may change. The next six sections take the rules one at a time, each with its trap.

Pagination: why offsets lose rows and cursors do not

An API never returns a million rows in one answer. It returns a page, and a way to ask for the next. There are two common ways.

Offset pagination asks for "100 rows, skipping the first 200". It is simple and fragile. If rows are added or deleted while you page through, every later page shifts, and you read some rows twice or miss them.

Cursor pagination asks for "100 rows after the row with this ID". The position is anchored to a specific record, not to a count, so inserts elsewhere in the list do not move it. Stripe's list endpoints work this way: you pass starting_after with the ID of the last object you received, the response tells you through has_more whether there is another page, and limit takes a value from 1 to 100. Lists come back in reverse chronological order, newest first.18

Example: three duplicates in one run

Callum's first draft paged through Stripe transactions with an offset, newest first, 100 per page. While page 1 (rows 1 to 100) was being written, three new payments arrived at the top of the list.

Page 2 asked for "skip 100, take 100". The list now had three extra rows at the top, so positions 101 to 200 now held what had been rows 98 to 197. Rows 98, 99 and 100 were read a second time. With deletions the error runs the other way and rows silently disappear.

With a cursor, page 2 asks for "the 100 rows after transaction txn_X", where txn_X is the last row of page 1. The three new payments sit above txn_X and do not shift anything below it. No duplicates, nothing missed, and the new payments are picked up by the next run.

Rate limits: how fast you may ask

Every API limits how many requests you may send in a period. Stripe's documentation lists a global limit of 100 requests per second per account in live mode, 25 per second in a sandbox, and 25 per second for most individual endpoints unless stated otherwise. Requests over the limit get the HTTP status 429 Too Many Requests.19 That status code was defined in 2012 in Request for Comments (RFC) 6585, which says the response may include a Retry-After header telling you how long to wait.20

The first step is arithmetic. Before a large job, work out how many requests it will make and how long it must take at a safe pace:

P=⌈NL⌉T=PrP = \left\lceil \frac{N}{L} \right\rceil \qquad T = \frac{P}{r}

Here PP is the number of page requests, NN is the number of rows to fetch, LL is the page size, the brackets ⌈ ⌉\lceil \, \rceil mean round up to the next whole number, TT is the minimum run time in seconds, and rr is the request rate you allow yourself per second. These are plain ratios, see Foundations: ratios and rates.

Example: the five year backfill from Stripe

Callum wants the full history: five years at about 1,640 balance transactions a month is N=98,400N = 98{,}400. The page size is L=100L = 100. He limits himself to r=5r = 5 requests a second, a fifth of the endpoint limit, so the shop's own checkout traffic to Stripe keeps all its headroom.

P=⌈98,400100⌉=984T=9845=196.8 secondsP = \left\lceil \frac{98{,}400}{100} \right\rceil = 984 \qquad T = \frac{984}{5} = 196.8 \text{ seconds}

So P=984P = 984 requests and TT is just over three minutes. The whole backfill fits comfortably into one run. Had he ignored the arithmetic and fired requests as fast as possible from eight parallel workers, he would have pushed against the global limit while the shop was taking payments, which is exactly the load Stripe asks integrations to avoid during analytical or migration work.19

Retries with exponential backoff and jitter

Some failures are temporary: a 429, a 500 or 503 from an overloaded server, a timeout, a dropped connection. The right response is to wait and try again. Other failures are permanent: a 400 (bad request), a 401 (wrong credentials), a 403 (not allowed), a 404 (not found). Retrying those wastes time and can hide a real fault. Retry the first group, fail fast on the second.

How long to wait matters more than it looks. The standard answer is capped exponential backoff: double the wait after each failure, up to a ceiling. Marc Brooker's 2015 article on the AWS Architecture Blog showed why that alone is not enough. When many clients fail at the same moment, they all back off by the same amounts and retry in synchronised waves. His fix is jitter, a random component in the wait. In the variant he calls Full Jitter, each client waits a random time between zero and the capped exponential value, which spreads the retries into a steady trickle.21

The capped exponential wait before retry number nn, and the actual wait drawn at random with full jitter, are:

wn=min⁡(c,  b⋅2n),Wn∼U(0, wn),E[Wn]=wn2w_n = \min\left(c,\; b \cdot 2^{n}\right), \qquad W_n \sim U(0,\, w_n), \qquad E[W_n] = \frac{w_n}{2}

Here wnw_n is the capped wait for retry nn (counting from n=0n = 0), bb is the base wait, cc is the cap, WnW_n is the jittered wait, U(0,wn)U(0, w_n) means a uniform random value between zero and wnw_n, and E[Wn]E[W_n] is its expected value, which for a uniform draw is the midpoint. The doubling is exponential growth, see Foundations: compounding, and the midpoint follows from Foundations: expected value.

If the server sends Retry-After, it knows better than your formula. Use its value. RFC 9110 allows that header to hold either a number of seconds or an HTTP date, so your code must read both.22

Example: six retries, and why the eight jobs stop colliding

Callum sets b=1b = 1 second, c=60c = 60 seconds and allows six retries, n=0n = 0 to 55. The capped waits are 1, 2, 4, 8, 16 and 32 seconds, 63 seconds in total. With full jitter, the expected waits are half of those:

∑n=05E[Wn]=1+2+4+8+16+322=31.5 seconds\sum_{n=0}^{5} E[W_n] = \frac{1 + 2 + 4 + 8 + 16 + 32}{2} = 31.5 \text{ seconds}

So ∑E[Wn]\sum E[W_n] is 31.5 seconds, and a job that fails six times in a row gives up after about half a minute of waiting on average, never more than 63 seconds. A seventh retry would have hit the cap, since 26=64>602^6 = 64 > 60.

Why jitter matters to Wrenfield: at 5am eight extraction jobs start together. Suppose a short outage at the source returns 503 to all eight at once. Without jitter, all eight retry at exactly 1 second, all fail again, all retry at exactly 3 seconds, and so on: eight requests arriving in the same instant every time, just as the source is recovering. With full jitter, the eight first retries are spread at random across the first second, the second retries across two seconds, and the load arrives as a trickle.

Grouped bars for retries 0 to 5 with a base of 1 second and a cap of 60 seconds. Capped exponential waits are 1, 2, 4, 8, 16 and 32 seconds, 63 seconds in total. The expected full jitter waits are half of each: 0.5, 1, 2, 4, 8 and 16 seconds, 31.5 seconds in total. Jitter halves the expected wait and spreads clients apart. Tap or click to open full screen and move around

Idempotency: running it twice must not count it twice

A job is idempotent when running it twice has the same effect as running it once. For ingestion this is the property that matters most, because every job will one day run twice: a retry after a timeout, a manual rerun after a bug fix, an orchestrator that restarts a task it thought had died.

For requests that change things in another system, APIs offer idempotency keys. You send a unique key with the request, and if the same request arrives again the server returns the first result instead of acting twice. Stripe accepts an Idempotency-Key header of up to 255 characters, suggests a version 4 universally unique identifier (UUID), and lets keys be removed after at least 24 hours.23 The Internet Engineering Task Force (IETF) is standardising the same header for HTTP in general; the November 2026 draft recommends a UUID or a similar random value as the key.24

For extraction, which only reads, the risk is on your side: loading the same rows twice. Three habits make an ingestion job idempotent:

  1. Fix the window at the start. The run reads "created from A to B", with B fixed when the run starts, not "everything up to now", which changes while the job runs.
  2. Append to raw, deduplicate in staging. The raw layer keeps every delivery, including the duplicates, which is the audit trail. The staging model keeps one row per business key, the newest.
  3. Move the watermark last. The watermark (the bookmark that says how far you have read) moves forward only after the data is safely written. A crash before that point means the next run reads the same window again, which step 2 makes harmless.

Example: the rerun on 3 January

On 3 January the 5am Stripe run writes its file with 812 rows (the window includes the 14 day lookback explained in the next section), then the BigQuery load fails on a quota error. Callum reruns the whole job at 9am. The second run reads the same window, because the watermark never moved, and writes a second file with the same 812 rows. Both files end up loaded.

Raw now holds 1,624 rows from the two batches. The staging model keeps one row per balance_transaction_id, choosing the latest extraction. Staging holds 812 for that window. Revenue is right. The raw layer shows, for anyone who asks, that the window was loaded twice and when.

Incremental reads with a cursor and a lookback

Reading everything every night works for small tables and is often the right first step. As tables grow, you read only what is new or changed since the last run, keeping a watermark: the highest creation or update time you have safely loaded.

Two details catch everyone. First, time stamps have limited precision. Stripe records creation times in whole seconds, so several objects can share one.11 If the next run asks for "created after the watermark" with a strict greater than, rows that share the watermark's second and arrived after the read are lost for ever. Ask for "greater than or equal" and let staging remove the overlap.

Second, a cursor on creation time sees new rows, not changed ones. A Stripe balance transaction has a status that moves from pending to available on its available_on date.25 A job that only asks for newly created transactions loads each one once, while it is still pending, and never sees it become available. The fix is a lookback: each run reads again a window reaching back further than any change you care about. This is where incremental loading gets subtle, and the next chapter in this series, on incremental loading and change data capture (CDC), goes through every trap in depth.

Example: a lookback of 14 days

Callum sets a lookback of 14 days, comfortably longer than the time between a Stripe charge and its payout on Wrenfield's account. Each night the job reads every balance transaction created in the last 14 days plus one night, about 820 rows, 9 pages (the 3 January run had 812). Staging keeps the latest version of each, so a transaction that became available on day 3 shows as available from day 3 onward.

The cost of the lookback is about 8 extra requests a night. The cost of no lookback would be a payout reconciliation that never matches. The reconciliation article shows what an unmatched number does to trust in a report.

Schema changes: the API will change under you

APIs change. Fields are added, renamed, deprecated and removed, and versions are retired. A loader that maps each field to a fixed column at the moment of loading breaks on the first new field, or worse, silently drops it.

The robust pattern follows from ELT. Land the whole object as received, as one JSON text per row, plus your metadata. Parse fields in the staging model. A new field then costs nothing until someone wants it. A removed or renamed field turns into a NULL in staging, which a test on that column catches the same morning. The chapter on data types, schemas and formats explains why renames are the change that breaks most pipelines.

Example: the field that appeared on a Tuesday

Imagine the payment provider adds a new field, balance_type, to balance transactions. Wrenfield's raw table stores each object as a JSON string, so the new field arrives inside the payload on the first night and nothing breaks. Nobody uses it yet.

Three weeks later Priya wants to know which balance it refers to. Callum adds one line to the staging model, json_value(payload, '$.balance_type') as balance_type, and reruns staging over the raw history. Every row from the day the field first appeared now has a value. Older rows have NULL, which is the truth: the field did not exist then. No backfill from the API was needed.

The extractor, in full

Here is the whole pattern in one place: a Python extractor for Stripe balance transactions with cursor pagination, a fixed window, a lookback, retries with full jitter, Retry-After support, and raw JSON Lines output with load metadata. JSON Lines means one complete JSON object per line, which makes large files easy to stream, split and append.26

Tap or click to open full screen and move around
"""Pull Stripe balance transactions into raw JSON Lines files.

Each run reads a fixed window [watermark minus lookback, start of run),
writes every object exactly as received plus load metadata, renames the
finished file, and only then moves the watermark. Safe to rerun:
staging keeps one row per balance transaction id.
"""
import json
import os
import random
import time
import uuid
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path

import requests

API = "https://api.stripe.com/v1/balance_transactions"
RETRYABLE = {429, 500, 502, 503, 504}
MAX_RETRIES = 6
BASE_SECONDS = 1.0
CAP_SECONDS = 60.0
LOOKBACK = timedelta(days=14)
PAUSE_SECONDS = 0.2  # about 5 requests a second
STATE = Path("state/stripe_balance_transactions.json")
OUT_DIR = Path("landing/stripe/balance_transactions")


def backoff_seconds(attempt: int) -> float:
    """Full jitter: a random wait between 0 and the capped exponential."""
    return random.uniform(0, min(CAP_SECONDS, BASE_SECONDS * 2 ** attempt))


def retry_after_seconds(response) -> float | None:
    """Retry-After holds either seconds or an HTTP date (RFC 9110)."""
    value = response.headers.get("Retry-After")
    if value is None:
        return None
    if value.strip().isdigit():
        return float(value)
    try:
        when = parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())


def get_page(session: requests.Session, params: dict) -> dict:
    for attempt in range(MAX_RETRIES + 1):
        try:
            response = session.get(API, params=params, timeout=(3.05, 30))
        except (requests.ConnectionError, requests.Timeout):
            if attempt == MAX_RETRIES:
                raise
            time.sleep(backoff_seconds(attempt))
            continue
        if response.status_code == 200:
            return response.json()
        if response.status_code in RETRYABLE and attempt < MAX_RETRIES:
            wait = retry_after_seconds(response)
            time.sleep(wait if wait is not None else backoff_seconds(attempt))
            continue
        response.raise_for_status()  # 400, 401, 403, 404: retrying cannot help
        raise RuntimeError(f"unexpected status {response.status_code}")
    raise RuntimeError("retries exhausted")


def write_atomically(path: Path, text: str) -> None:
    tmp = path.with_suffix(".tmp")
    tmp.write_text(text, encoding="utf-8")
    os.replace(tmp, path)


def run() -> None:
    state = json.loads(STATE.read_text()) if STATE.exists() else {"watermark": 0}
    started = datetime.now(timezone.utc)
    window_start = max(0, int(state["watermark"] - LOOKBACK.total_seconds()))
    window_end = int(started.timestamp())
    batch_id = str(uuid.uuid4())

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    final = OUT_DIR / f"{started:%Y%m%d}_{batch_id}.jsonl"
    partial = final.with_suffix(".part")

    session = requests.Session()
    session.auth = (os.environ["STRIPE_API_KEY"], "")
    params = {"limit": 100, "created[gte]": window_start, "created[lt]": window_end}

    rows = 0
    with partial.open("w", encoding="utf-8") as out:
        while True:
            page = get_page(session, params)
            for obj in page["data"]:
                out.write(json.dumps({
                    "_batch_id": batch_id,
                    "_extracted_at": started.isoformat(sep=" "),
                    "_source": "stripe.balance_transactions",
                    "_window_start": window_start,
                    "_window_end": window_end,
                    "payload": json.dumps(obj, separators=(",", ":")),
                }) + "\n")
                rows += 1
            if not page["has_more"]:
                break
            params["starting_after"] = page["data"][-1]["id"]
            time.sleep(PAUSE_SECONDS)

    os.replace(partial, final)  # the file appears complete or not at all
    STATE.parent.mkdir(parents=True, exist_ok=True)
    write_atomically(STATE, json.dumps(
        {"watermark": window_end, "last_batch": batch_id, "rows": rows}))
    print(f"{rows} rows written to {final}")


if __name__ == "__main__":
    run()

A few choices deserve a word for anyone new to this kind of code.

The timeout=(3.05, 30) gives the connection 3.05 seconds to open and the server 30 seconds to answer. The Requests documentation warns that requests "do not time out unless a timeout value is set explicitly", so a script without one can hang for minutes or more, and suggests a connect timeout slightly above a multiple of 3 seconds, the default Transmission Control Protocol (TCP) packet retransmission window.27

The .part file is renamed to .jsonl only when the last page has been written. A loader that picks up *.jsonl files never sees half a file. The state file is written the same way, through a temporary file and a rename, so a crash cannot leave a half written watermark.

The payload is the Stripe object as a JSON string, untouched. Every parsing decision happens later, in SQL, where it can be changed and rerun.

The created[lt] bound is fixed when the run starts. Payments that arrive during the run belong to the next window, and that is what makes two runs over the same window return the same rows.

Stripe authenticates with the secret key as the user name of HTTP basic authentication, which is what session.auth sends.18 Keep the key in the environment or a secret store, never in the code, and use a restricted key that can only read.

Example: loading the file and reading it back

The file goes to a Cloud Storage bucket in the London region and from there into BigQuery with a load job, which costs nothing on the shared slot pool.4 The bq load command accepts newline delimited JSON with a schema file:28

bq load \
  --location=europe-west2 \
  --source_format=NEWLINE_DELIMITED_JSON \
  raw_stripe.balance_transactions \
  "gs://wrenfield-landing/stripe/balance_transactions/20270128_*.jsonl" \
  ./raw_envelope_schema.json
[
  {"name": "_batch_id", "type": "STRING", "mode": "REQUIRED"},
  {"name": "_extracted_at", "type": "TIMESTAMP", "mode": "REQUIRED"},
  {"name": "_source", "type": "STRING", "mode": "REQUIRED"},
  {"name": "_window_start", "type": "INTEGER", "mode": "REQUIRED"},
  {"name": "_window_end", "type": "INTEGER", "mode": "REQUIRED"},
  {"name": "payload", "type": "STRING", "mode": "REQUIRED"}
]

The dbt staging model parses the payload with BigQuery's JSON_VALUE, which accepts a JSON formatted string,29 and keeps one row per transaction:

-- models/staging/stripe/stg_stripe__balance_transactions.sql
-- BigQuery dialect
with parsed as (
    select
        json_value(payload, '$.id')                         as balance_transaction_id,
        json_value(payload, '$.type')                       as transaction_type,
        json_value(payload, '$.status')                     as status,
        cast(json_value(payload, '$.amount') as int64)      as amount_minor,
        cast(json_value(payload, '$.fee') as int64)         as fee_minor,
        cast(json_value(payload, '$.net') as int64)         as net_minor,
        upper(json_value(payload, '$.currency'))            as currency,
        timestamp_seconds(cast(json_value(payload, '$.created') as int64))      as created_at,
        timestamp_seconds(cast(json_value(payload, '$.available_on') as int64)) as available_on,
        json_value(payload, '$.source')                     as source_object_id,
        _batch_id,
        _extracted_at
    from {{ source('stripe', 'balance_transactions') }}
)

select *
from parsed
qualify row_number() over (
    partition by balance_transaction_id
    order by _extracted_at desc
) = 1

After the rerun on 3 January, a quick check shows the effect:

LayerRows for the 3 January windowDistinct transaction IDs
raw_stripe.balance_transactions1,624812
stg_stripe__balance_transactions812812

Amounts stay in minor units (pence) until a later model divides by 100 for display, for the reasons the chapter on data types gives about money and floating point numbers.

Example: testing the fragile parts first

The parts of an extractor that break quietly are the small functions: the header parser and the backoff. They are also the easiest to test, so Callum writes the tests first, with pytest:

# tests/test_extract_stripe.py
import random
from datetime import datetime, timedelta, timezone
from email.utils import format_datetime

import extract_stripe as ex


class FakeResponse:
    def __init__(self, headers):
        self.headers = headers


def test_retry_after_in_seconds():
    assert ex.retry_after_seconds(FakeResponse({"Retry-After": "120"})) == 120.0


def test_retry_after_as_http_date():
    when = datetime.now(timezone.utc) + timedelta(seconds=30)
    header = format_datetime(when, usegmt=True)
    assert 28 <= ex.retry_after_seconds(FakeResponse({"Retry-After": header})) <= 30


def test_missing_retry_after_means_use_backoff():
    assert ex.retry_after_seconds(FakeResponse({})) is None


def test_backoff_stays_between_zero_and_the_cap():
    random.seed(7)
    waits = [ex.backoff_seconds(n) for n in range(20)]
    assert all(0 <= w <= ex.CAP_SECONDS for w in waits)

The HTTP date test is the one that matters: a parser that only expects seconds turns Fri, 29 Jan 2027 05:00:30 GMT into an exception at the worst possible moment, during an incident at the source. A later chapter on testing data pipelines builds the full test suite around this.

Files: SFTP and object storage

Not every source has an API. The 3PL drops a CSV on an SSH File Transfer Protocol (SFTP) server every morning. PayPal can deliver its reconciliation reports to an SFTP dropbox on a subscription, or offer them for download from its reporting dashboard.30 Supplier feeds arrive as CSV or XML files over HTTPS. Files bring their own traps.

A file can be picked up while it is still being written. The fix is to wait for a signal that it is complete: a marker file the sender writes afterwards, a rename from a temporary name, or a size that stays the same across two listings.

The same name can arrive twice with different content, or different names with the same content. Name your landed copies by content, not by the sender's file name: a SHA 256 checksum of the bytes identifies the file whatever it is called.

The bytes must be kept as they are. The 3PL's file is Windows 1252 encoded with semicolons, and uses its own stock keeping unit (SKU) format with a prefix. Converting it to UTF 8 on the way in feels helpful and destroys the evidence when a character later looks wrong. Land the original bytes, record the encoding in the manifest, and decode in staging. The chapter on where raw data comes from shows how to read exactly this file with explicit encoding and delimiter.

Example: the returns file that arrived twice

The 3PL uploads returns_20270127.csv at 6.10am. At 6.40am it uploads a corrected file with the same name, because the first one missed four rows. Callum's job runs at 7am:

# ingest_3pl.py: land new 3PL files byte for byte, once per distinct content
import hashlib
import time
from datetime import datetime, timezone
from pathlib import Path

import paramiko


def land_new_files(host, user, key_file, remote_dir, landing_dir, known_hashes):
    client = paramiko.SSHClient()
    client.load_system_host_keys()  # trust only known hosts, never auto add
    client.connect(host, username=user, key_filename=key_file)
    sftp = client.open_sftp()
    landed = []
    try:
        before = {a.filename: a.st_size for a in sftp.listdir_attr(remote_dir)}
        time.sleep(60)  # a file still being written changes size
        after = {a.filename: a.st_size for a in sftp.listdir_attr(remote_dir)}
        for name, size in after.items():
            if not name.lower().endswith(".csv") or before.get(name) != size:
                continue  # not a CSV, or still growing: next run
            tmp = Path(landing_dir) / f".{name}.part"
            sftp.get(f"{remote_dir}/{name}", str(tmp))
            digest = hashlib.sha256(tmp.read_bytes()).hexdigest()
            if digest in known_hashes:
                tmp.unlink()  # same bytes as a file already landed
                continue
            final = Path(landing_dir) / f"{digest[:16]}_{name}"
            tmp.rename(final)
            landed.append({
                "source_file": name,
                "sha256": digest,
                "bytes": size,
                "encoding": "cp1252",
                "delimiter": ";",
                "landed_at": datetime.now(timezone.utc).isoformat(sep=" "),
            })
    finally:
        sftp.close()
        client.close()
    return landed  # the caller appends these rows to the load manifest

Paramiko's listdir_attr returns the attributes of each file, including st_size, and get copies a remote file to a local path.31 The first upload was landed at 6.30am by the earlier run under its checksum. The corrected file has different bytes, so a different checksum, and is landed as a second file. Both are in raw. Staging takes the latest version of each return by the 3PL's return reference, so the four missing rows appear, and the manifest shows exactly which file brought them.

Object storage (Amazon S3, Google Cloud Storage, Azure Blob Storage) follows the same rules: land by content, keep the bytes, record a manifest. Cloud Storage can also notify a subscriber when a new object lands, which turns a file drop into a push.32

The shop database: the source closest to home

The richest source is the shop's own PostgreSQL database: spree_orders, spree_line_items, spree_payments, spree_refunds, spree_return_items, spree_users and the rest. Three rules keep its extraction safe.

Never run heavy extraction queries against the primary database that takes the orders. Use a read replica, a copy kept up to date by PostgreSQL's replication, so a slow query hurts nobody's checkout. PostgreSQL's documentation calls a replica that accepts read queries a hot standby.33

Extract by updated_at with a lookback, exactly as with the API. Remember that Rails sets updated_at when a record is saved normally, but update_columns leaves it alone unless called with touch: true, and a bulk update in plain SQL never touches it.34 Deletes leave no trace at all in a query. Those gaps are why change data capture exists. The next chapter covers it, using PostgreSQL logical replication and Debezium.

Keep the first version boring. For about 66 orders a day, a nightly COPY of changed rows to a file, landed and loaded like any other, is enough for years. The earlier article on setting up BigQuery for a Rails and Solidus shop shows a nightly export in Rails, and the article on the shop database as the source of truth explains why the order table, not the analytics tag, is the number that counts.

Example: the nightly order extraction

-- export_orders.sql, PostgreSQL, run against the read replica at 5am:
-- psql "$REPLICA_URL" -v ON_ERROR_STOP=1 -v since='2027-01-26 05:00:00+00' \
--      -f export_orders.sql > spree_orders_20270128.csv
-- :since is the last watermark minus a 2 day lookback.
copy (
  select o.id, o.number, o.state, o.payment_state, o.shipment_state,
         o.total, o.item_total, o.adjustment_total, o.currency,
         o.completed_at, o.updated_at, o.user_id, o.email
  from spree_orders o
  where o.updated_at >= :'since'
) to stdout with (format csv, header true, encoding 'UTF8');

PostgreSQL's COPY writes the result of a query in CSV format. With TO STDOUT the rows stream back to psql, so the file lands on the machine where the job runs rather than on the database server.35 On a normal night this returns about 66 new orders plus around 140 orders whose state changed: shipped, refunded, returned. All of them land in raw. Staging keeps the newest version of each order. The email column is there because the customer chapter needs it for matching duplicates. If it were not needed, it would not be selected, which is the data minimisation rule from earlier applied in one line.

Reverse ETL in one paragraph

Data also moves the other way. Reverse ETL means sending results from the warehouse back into operational tools: a customer segment into the newsletter tool, a predicted lifetime value into the ad platforms, a "high return risk" flag into the customer service tool. The same rules apply in reverse, with one more: the target system is someone's live work tool, so a bad sync is felt by staff and customers at once, not just in a report. Send only the fields the tool needs, make every sync idempotent by keying on the customer ID, and respect the consent each customer gave. The older article on a data warehouse for marketing automation shows what that loop can do.

Example: the segment that went out twice

Callum sends a "bought twice, not in 120 days" segment to the newsletter tool every Monday. The first version created contacts with a POST call. When the job retried after a timeout, 312 customers were created twice and two of them complained about the duplicate email. The fix was to upsert by email through the tool's update endpoint, which is idempotent by design: running it twice leaves one contact with the latest values. The Monday sync now has a rerun button that anyone can press.

A decision table for every source of the example shop

Here is where Callum lands for Wrenfield Home. It is the result of the questions in this chapter, asked source by source: who needs it how fast, who moves first, does a native export or connector fit, and what could go wrong when it runs twice.

SourceHow it movesPush or pullRhythmBuilt or boughtWhy
Shop database (Solidus on PostgreSQL)COPY of changed rows from a read replica, later CDCPullDaily at 5amOwn codeSmall volume, full control, CDC when deletes matter
GA4BigQuery daily exportPush (by Google)DailyNativeComplete daily tables, streaming is best effort
Google AdsBigQuery Data Transfer ServicePull (by Google)Daily, 7 day refresh windowNativeReads recent days again as conversions settle
Meta AdsManaged connector, daily reports with a lookbackPullDailyBoughtAPI changes often, connector absorbs them
StripeAPI extractor or connector, plus webhooks in the shopPull, with push for operationsDaily, payment failures hourlyEitherPull for the books, push for speed
PayPalReconciliation report files via SFTPPullDailyOwn codeFiles, not an API
3PL shipments and returnsCSV via SFTP, landed byte for bytePullDaily at 7amOwn codeOwn format, Windows 1252, late returns
Supplier feedsCSV and XML over HTTPSPullDailyOwn codeOne feed in mm, others in cm, decode in staging
Newsletter toolManaged connectorPullDailyBoughtStandard API, standard tables
Customer service toolConnector, 9 fields onlyPullDailyBoughtMinimisation: no message bodies
Marketing cost spreadsheetBigQuery external table on the Google SheetPullOn queryNativeNo code, snapshot daily into raw

Two things stand out. Most of the table says "daily", and nobody at Wrenfield is worse off for it. And the custom code lives where the sources are unusual, the shop database and the files, while standard sources use standard tools.

The scheduler that runs all of this, with dependencies, retries and backfills, is the subject of the chapter on orchestration later in this series.

Conclusion

Data movement looks like a speed problem and is really a reliability problem. Load first and transform inside the warehouse (ELT), because the raw copy is what lets you correct every rule you will ever get wrong. Transform before loading only where you must: personal data you have no reason to keep, data you may never store, and volume nobody will query.

Choose the rhythm by who acts on the number and how fast. For a shop the size of Wrenfield, daily batch with one or two hourly jobs is the honest default, and streaming belongs to the few jobs that act within seconds. Pull for the truth, push for speed, and let a scheduled pull sweep up what a push missed.

Buy connectors for standard sources, write your own code for unusual ones, and remember that maintenance, not the build, is the cost that lasts. When you talk to an API, use cursors, respect the rate limit, retry only what is temporary with capped exponential backoff and jitter, read Retry-After in both its forms, and make every run idempotent: a fixed window, raw appends, deduplication in staging, and a watermark that moves last. Do that, and the day a job runs twice is a non event instead of a restatement.

If your data arrives by a mix of exports, scripts and hope, book the free workshop: we map every source of your shop to the right way of moving it, and the first two weeks of work are on me.

Sources

  1. 1.

    Ralph Kimball and Joe Caserta, The Data Warehouse ETL Toolkit: Practical Techniques for Extracting, Cleaning, Conforming, and Delivering Data, Wiley, September 2004, https://www.wiley.com/en-gb/The+Data+Warehouse+ETL+Toolkit%3A+Practical+Techniques+for+Extracting%2C+Cleaning%2C+Conforming%2C+and+Delivering+Data-p-9780764567575

  2. 2.

    Sergey Melnik, Andrey Gubarev, Jing Jing Long, Geoffrey Romer, Shiva Shivakumar, Matt Tolton and Theo Vassilakis, Dremel: Interactive Analysis of Web Scale Datasets, Proceedings of the 36th International Conference on Very Large Data Bases, 2010, pages 330 to 339, https://research.google/pubs/dremel-interactive-analysis-of-web-scale-datasets-2/

  3. 3.

    Google, [GA4] Set up BigQuery Export, Analytics Help, accessed 23 November 2026, https://support.google.com/analytics/answer/9358801

  4. 4.

    Google Cloud, BigQuery pricing, accessed 23 November 2026, https://cloud.google.com/bigquery/pricing

  5. 5.

    UK GDPR, Article 5, Principles relating to processing of personal data, legislation.gov.uk, https://www.legislation.gov.uk/eur/2016/679/article/5

  6. 6.
  7. 7.

    Apache Spark, Structured Streaming Programming Guide, overview, https://spark.apache.org/docs/latest/streaming/index.html

  8. 8.

    Tyler Akidau, Streaming 101: The world beyond batch, O'Reilly Radar, 5 August 2015, https://www.oreilly.com/radar/the-world-beyond-batch-streaming-101/

  9. 9.

    Nathan Marz, How to beat the CAP theorem, 13 October 2011, http://nathanmarz.com/blog/how-to-beat-the-cap-theorem.html

  10. 10.

    Jay Kreps, Questioning the Lambda Architecture, O'Reilly Radar, 2 July 2014, https://www.oreilly.com/radar/questioning-the-lambda-architecture/

  11. 11.

    Stripe, Receive Stripe events in your webhook endpoint (automatic retries, duplicate events, event ordering, signature verification), Stripe Docs, accessed 23 November 2026, https://docs.stripe.com/webhooks

  12. 12.

    Google Cloud, Google Ads transfers (repeat frequency and refresh window), BigQuery Data Transfer Service documentation, accessed 23 November 2026, https://cloud.google.com/bigquery/docs/google-ads-transfer

  13. 13.

    Google Cloud, Create Google Drive external tables, BigQuery documentation, https://cloud.google.com/bigquery/docs/external-data-drive

  14. 14.

    Fivetran, Usage based pricing: Monthly Active Rows, Fivetran documentation, accessed 23 November 2026, https://fivetran.com/docs/usage-based-pricing

  15. 15.

    Fivetran, Pricing, accessed 23 November 2026, https://www.fivetran.com/pricing

  16. 16.

    Stitch, Pricing, accessed 23 November 2026, https://www.stitchdata.com/pricing/

  17. 17.

    Airbyte, Platform documentation (plans: self managed Core, cloud and hybrid), accessed 23 November 2026, https://docs.airbyte.com/platform/

  18. 18.

    Stripe, API reference: Pagination, Stripe Docs, accessed 23 November 2026, https://docs.stripe.com/api/pagination

  19. 19.

    Stripe, Rate limits, Stripe Docs, accessed 23 November 2026, https://docs.stripe.com/rate-limits

  20. 20.

    Mark Nottingham and Roy Fielding, RFC 6585: Additional HTTP Status Codes, section 4, 429 Too Many Requests, IETF, April 2012, https://www.rfc-editor.org/rfc/rfc6585

  21. 21.

    Marc Brooker, Exponential Backoff And Jitter, AWS Architecture Blog, 4 March 2015, https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

  22. 22.

    Roy Fielding, Mark Nottingham and Julian Reschke, RFC 9110: HTTP Semantics, section 10.2.3, Retry After, IETF, June 2022, https://www.rfc-editor.org/rfc/rfc9110

  23. 23.

    Stripe, API reference: Idempotent requests, Stripe Docs, accessed 23 November 2026, https://docs.stripe.com/api/idempotent_requests

  24. 24.

    J. Jena, S. Dalal and D. Tishkin, The Idempotency Key HTTP Header Field, Internet Draft draft-ietf-httpapi-idempotency-key-header-09, IETF, 21 November 2026, https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/

  25. 25.

    Stripe, API reference: List all balance transactions, Stripe Docs, accessed 23 November 2026, https://docs.stripe.com/api/balance_transactions/list

  26. 26.

    JSON Lines, documentation of the format, https://jsonlines.org/

  27. 27.

    Requests, Advanced usage: Timeouts, Requests documentation, https://requests.readthedocs.io/en/latest/user/advanced/

  28. 28.

    Google Cloud, Loading JSON data from Cloud Storage, BigQuery documentation, https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-json

  29. 29.

    Google Cloud, JSON functions in GoogleSQL, BigQuery documentation, https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions

  30. 30.

    PayPal, Reports overview and SFTP reports, PayPal Developer, accessed 23 November 2026, https://developer.paypal.com/docs/reports/sftp-reports/

  31. 31.

    Paramiko, SFTP client documentation, https://docs.paramiko.org/en/latest/api/sftp.html

  32. 32.

    Google Cloud, Pub/Sub notifications for Cloud Storage, https://cloud.google.com/storage/docs/pubsub-notifications

  33. 33.

    PostgreSQL Global Development Group, Hot Standby, PostgreSQL documentation, https://www.postgresql.org/docs/current/hot-standby.html

  34. 34.

    Ruby on Rails, ActiveRecord::Persistence API documentation (save, update_columns and the touch option), https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html

  35. 35.

    PostgreSQL Global Development Group, COPY, PostgreSQL documentation, https://www.postgresql.org/docs/current/sql-copy.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.