Where raw data comes from, and why it is never clean
TL;DR
Difficulty: Beginner
Raw data is the by product of running a business, written by each system for its own job, so it is never clean when it arrives.
- The shop database keeps the present and overwrites the past: every extract is a snapshot.
- APIs page, throttle, expire versions and use their own units (Google Ads money comes in micros).
- The GA4 export is nested events, revised for up to three days, and misses visitors who decline consent.
- Webhooks arrive twice, late and out of order: store event ids and never let an old event overwrite a newer state.
- Partner files and spreadsheets carry habits, not contracts: delimiters, encodings, local times, own codes.
- Read every file as text first, then convert each column with an explicit rule, and keep the original untouched.
What to read first
One order at an online shop leaves a trace in nine systems, and no two of them describe it the same way. This chapter walks through every kind of source a shop's data comes from, the dirt that is typical for each, how file formats and character encodings really work, and how to read a partner's awkward CSV file in Python and PostgreSQL without letting any tool guess.
Raw data is a by product of running the business
Nobody at an online shop sets out to produce data. Priya, who runs Wrenfield Home in Leeds, sets out to sell lamps, cushions and throws. Every time she does, a handful of systems write something down along the way: the shop records the order, Stripe records the payment, Google Analytics records the visit, the warehouse records the parcel. Each of those records was written for that system's own job, by that system's own rules, at that system's own moment. None of them was written for a report.
That is the whole answer to the question in the title, and the rest of this chapter is the detail. Raw data is the exhaust of operations. It is shaped by the forms people type into, by the software versions that happened to be running, by the clocks on different servers and by the habits of whoever built each integration. It arrives clean only when somebody made it clean on purpose, and in a small business that somebody usually does not exist yet.
This chapter walks through every kind of source a shop like Wrenfield Home has, what each one gets wrong in a typical way, how the common file formats and character encodings work, and why data is born dirty in the first place. It ends with working code: reading the warehouse's awkward CSV file correctly in Python and in PostgreSQL. If you have not read the first chapter yet, what a data engineer actually does sets out the whole pipeline this chapter feeds, and what dirty data costs explains why any of this matters to the bottom line.
Example: one order, nine versions of the truth
Take one real looking order at Wrenfield Home (invented, like everything about this shop). On Tuesday 3 November 2026 at 9.02am, a customer called Siobhán buys two cushions for £72.00 including VAT. Callum, Wrenfield's developer and data engineer, traces that one order through every system the next morning. Here is what each system says.
| System | What it recorded | How it identifies the order | Time it shows |
|---|---|---|---|
| Shop database (Solidus) | Order R482915630, state complete, total 72.00 | number = R482915630 | 09:02 UTC |
| GA4 BigQuery export | One purchase event, value 72 | ecommerce.transaction_id = R482915630 | event time in microseconds, UTC |
| Stripe | A payment of 7200 in the smallest currency unit (pence), fee deducted later | its own payment id, order number in metadata | Unix seconds |
| Stripe payout file | Part of a payout that lands on a later day, net of fees | payout id | payout date |
| 3PL warehouse CSV | Two lines, one per cushion, SKU with a WRF- prefix | order_ref | 03/11/2026 09:14, local time, no zone |
| Newsletter tool | Siobhán's email, a "customer" tag | email address | its own export time |
| Google Ads | One conversion worth 72 on the day of the ad click, four days earlier | click id | click date |
| Customer service tool | Nothing yet | ticket id | not applicable |
| Marketing cost sheet | Nothing per order, a monthly total typed by hand | none | month name |
Nine systems. Four different ways to write the same £72 (72.00, 72, 7200, and a net figure after fees). The 7200 is not a typo: Stripe's API expresses amounts in the currency's smallest unit, so £72.00 is 7200 pence.1 Five different time conventions. Three different identifiers for the same order, and two systems that cannot be joined to it at all. Nothing here is a bug. Every system did its job. The dirt only appears when you try to put them side by side, and putting them side by side is exactly what a report does.
The shop database is your best source, and it still has its own dirt
The shop's own database is the most trustworthy source you have, because it is where the business actually happens. Solidus, the open source eCommerce framework Wrenfield runs on Ruby on Rails, keeps orders in a table called spree_orders, their lines in spree_line_items, and so on. When I build a shop, this database is the system of record, and the shop database as the source of truth explains why every purchase event should come from it.
But "trustworthy" is not "ready for analysis". A shop database is an OLTP system, short for online transaction processing. It is designed to write one order quickly and safely, and to answer questions about the present: what is in this basket, has this order shipped. It is not designed to remember the past or to answer questions across millions of rows. That design shows up as four kinds of dirt.
- It stores the current state, not the history. When an order is cancelled, Solidus moves its
statefromcompletetocanceledand fillscanceled_at.2 The row is updated in place. Monday's report and Friday's report can both be correct and still disagree, because the row changed in between. - It stores what the application needed, not what you need. A guest checkout has an
emailbut nouser_id. That is structural: the field is empty because it does not apply, not because something went wrong. - It carries its own history of changes. Wrenfield's five years include a migration from an older platform. That import stored prices as floating point numbers and countries as free text ("UK", "United Kingdom", "England", "GB"). The schema today is clean. The rows from 2021 are not.
- It contains rows that are not business. About 40 test and staff orders a year sit in the same table as real ones.
Example: the October revenue that moved
On Monday 2 November Callum runs this query (PostgreSQL) for October, and Priya writes the result into her board pack.
-- PostgreSQL: completed orders in October, grouped by their state today
SELECT state,
count(*) AS orders,
sum(total) AS revenue_incl_vat
FROM spree_orders
WHERE completed_at >= '2026-10-01 00:00:00'
AND completed_at < '2026-11-01 00:00:00'
GROUP BY state
ORDER BY orders DESC;
| state | orders | revenue_incl_vat |
|---|---|---|
complete | 1,960 | 141,120.00 |
awaiting_return | 12 | 864.00 |
canceled | 8 | 576.00 |
On Friday the same query returns 1,953 complete orders, 15 awaiting return, 4 returned and 8 cancelled. Nobody made a mistake. Seven complete orders moved into the return process during the week, and four of those finished it. The database answered a slightly different question each time: "what state are October's orders in right now?"
Two lessons follow. First, any number taken from an operational database is a snapshot, so write down when it was taken. Second, if you want to explain last month's number next month, you need to keep the history yourself, either by copying the table every night or by capturing every change. Later chapters on loading data and on keeping history cover both properly. For now, the habit that costs nothing is a timestamp on every extract.
One more detail worth knowing on the first day: Rails stores timestamps in the database as UTC by default (the default_timezone setting is :utc unless someone changed it).3 That is the right choice, and it is also the reason the shop and the warehouse disagree about what time anything happened, as you will see below.
Third party APIs page, throttle and change under you
An API, short for application programming interface, is a door another company opens so your code can ask its system for data. Google Ads and Meta both offer one for campaign costs, clicks and conversions. An API feels cleaner than a file because the data comes back in tidy JSON. It brings its own set of problems, and almost every one of them causes silently missing rows rather than loud errors.
Pagination. An API never hands you a million rows at once. It hands you a page and a token for the next one. Google Ads returns pages of up to 10,000 rows, and the token for the next page expires if it is not used within about two hours.4 Meta's Graph API uses cursors, links to the next and previous page, and says plainly that your app should not store cursors, because they can become invalid.5 A loop that stops early, or a job that pauses overnight and then resumes with an old token, loses rows without an error.
Rate limits. Every API caps how fast you may call it. Google Ads rejects calls that go too fast with the error RESOURCE_TEMPORARILY_EXHAUSTED and asks you to retry with exponential backoff and random jitter, and the exact limit varies with the load on Google's side.6 Meta reports your usage in response headers such as X-Business-Use-Case-Usage and throttles each ad account separately.7 A script that ignores these limits either fails halfway or, worse, catches the error and carries on with half the data.
Versions that expire. APIs change their fields and retire old versions. Google Ads aims to keep each major version alive for around 12 months and to keep at most five versions available at once.8 Meta guarantees each Graph API version for at least two years.9 An integration nobody touches will stop working on a date someone else chose.
Units and definitions that are not yours. Google Ads returns money in micros: one million micros make one unit of currency.10 And a conversion in the standard Google Ads columns is dated to the day of the ad click, not the day of the purchase.11 So the figures for last week keep moving for a while after last week ends.
Example: how many requests a cost report needs
Callum pulls daily keyword costs for Wrenfield's 1,200 active keywords for the last 30 days, so the result has one row per keyword per day. The number of pages, and so the number of requests when using paged search, is the number of rows divided by the page size, rounded up. If you want the rule behind ratios like this, see Foundations: ratios and rates.
Here is the number of requests (pages), is the number of rows the report returns, is the page size of the API, and means "round up to the next whole number".
Worked through: rows, , so , rounded up to requests. If the job crashes after the third request, the data has 30,000 rows and looks perfectly plausible: 30 days, sensible costs, no error. The last 6,000 rows are simply missing. That is why Callum checks the row count against a second number every time (more on that in a moment), and why Google itself recommends the streaming variant for multi page reports, which returns all rows over one connection without page tokens.12
Here is the shape of his extract, using the official Google Ads Python client. Note the conversion from micros, and note that it pulls the last 30 days every night rather than only yesterday, because recent conversion figures are still moving.
# Python, google-ads client library: daily cost per campaign, last 30 days
from datetime import datetime, timezone
QUERY = """
SELECT segments.date, campaign.id, campaign.name,
metrics.cost_micros, metrics.clicks, metrics.conversions_value
FROM campaign
WHERE segments.date DURING LAST_30_DAYS
"""
def extract_costs(client, customer_id):
ga_service = client.get_service("GoogleAdsService")
pulled_at = datetime.now(timezone.utc).isoformat()
rows = []
for batch in ga_service.search_stream(customer_id=customer_id, query=QUERY):
for row in batch.results:
rows.append({
"date": row.segments.date,
"campaign_id": row.campaign.id,
"campaign_name": row.campaign.name,
"cost_micros": row.metrics.cost_micros, # keep the raw integer
"clicks": row.metrics.clicks,
"conversions_value": row.metrics.conversions_value,
"pulled_at": pulled_at, # when this snapshot was taken
})
return rows
Two choices in that code matter more than they look. It keeps cost_micros as the raw integer the API sent, and the conversion to pounds (divide by 1,000,000) happens later, in one place, where it can be tested. And every row carries pulled_at, so when the figure for 28 October changes between Tuesday's pull and Wednesday's, both versions can be kept and explained.
Analytics exports are events, not orders
Google Analytics 4 (GA4) can export every raw event into BigQuery, Google's cloud data warehouse, once a day. The daily table is called events_YYYYMMDD, and a separate events_intraday_YYYYMMDD table fills up during the day and is deleted once the daily table is complete.13 I set this up for shops routinely, and Google BigQuery for a Rails and Solidus shop walks through it.
The export is detailed, and it is dirty in ways that are easy to miss.
- It is shaped for events, not for questions. Parameters such as the page address are not columns. They sit in a repeated record called
event_params, each with akeyand avaluethat has separate fields for strings, integers and doubles.14 Asking for "the page" means unpacking that list every time. - A day is not finished when it ends. Google may keep updating a daily table with late events for up to three days after its date, and events arriving after that are not recorded at all.14 A report built at 6am on the 4th may not match one built on the 7th.
- There is a ceiling. Standard (free) GA4 properties have a daily export limit of 1 million events.13 Wrenfield's 110,000 sessions a month are well inside it, but a busy shop on the free tier can hit it.
- It only sees people who let it. Consent choices and ad blockers mean some visitors never send events. At Wrenfield, GA4 shows about 15% fewer purchases than the shop database. Cookies, consent and the ePrivacy mess explains why, and when analytics, ads and orders disagree shows how to reconcile them.
Example: measuring how much of reality GA4 sees
Callum counts October purchases in the export (BigQuery GoogleSQL dialect):
-- BigQuery: distinct purchase transactions per day in October
SELECT
event_date,
COUNT(DISTINCT ecommerce.transaction_id) AS purchases
FROM `wrenfield-analytics.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261001' AND '20261031'
AND event_name = 'purchase'
GROUP BY event_date
ORDER BY event_date;
He counts distinct transaction ids rather than events, because a customer who reloads the confirmation page can send the same purchase twice, a problem the purchase event done right deals with at the source. The October total comes to 1,683. The shop database says 1,980 completed orders. The share of real orders that GA4 sees is a simple ratio, explained in Foundations: ratios and rates.
Here is the coverage (the share of real orders that the analytics tool records), is the number of distinct purchase transactions in the GA4 export for the period, and is the number of completed orders in the shop database for the same period.
Worked through: , so GA4 sees 85% of orders and misses 15%. That number is not dirt to be cleaned away. It is a property of the source, and it belongs next to every GA4 figure. A conversion rate from GA4 uses GA4's own sessions and GA4's own purchases, so it is internally consistent. A revenue figure from GA4 is 15% short, and anyone who adds it to costs from the shop or from Google Ads mixes two different worlds.
Webhooks arrive twice, late and out of order
A webhook is the opposite of an API call. Instead of your code asking, the other system tells you: when a payment succeeds, Stripe sends an HTTP request to an address on your shop. It feels immediate and reliable. It is neither, by design.
Stripe's own documentation is unusually clear about this. In live mode Stripe retries a failed delivery for up to three days with exponential backoff. An endpoint "might occasionally receive the same event more than once". And Stripe "doesn't guarantee the delivery of events in the order that they're generated", so it advises tracking event ids to spot duplicates and fetching the current object from the API when an event arrives before the one it depends on.15 Those three behaviours, retries, duplicates and disorder, are true of most webhook senders, not only Stripe.
The trap is a handler that treats each webhook as a command: "payment succeeded, mark the order paid". Delivered twice, it marks it paid twice, which may send two confirmation emails. Delivered after a refund, it overwrites the refund.
Example: the payment that came back after the refund
Here is what happens to order R482915630 with a naive handler, step by step (times invented).
| Time | What Stripe sends | Naive handler does | Order shows |
|---|---|---|---|
| 09:02:05 | payment_intent.succeeded, event A | Marks order paid, but answers too slowly, so Stripe records the delivery as failed | paid, £72 |
| 09:40:11 | charge.refunded, event B (Siobhán cancelled by phone) | Marks order refunded | refunded |
| 10:03:20 | Event A again, the automatic retry | Marks order paid again | paid, £72 |
The order now says paid. Revenue is £72 too high, and the warehouse may pick and ship cushions that have already been refunded. Every step was correct on its own. The fix has two parts: remember every event id you have already processed, and never let an old event overwrite a newer state. The flow below is the shape Callum uses.
In Rails, the receiving end is short. The unique index on the event id does the duplicate detection, inside the database, so two deliveries arriving at the same moment cannot both slip through.
# db/migrate/20261104090000_create_webhook_events.rb
class CreateWebhookEvents < ActiveRecord::Migration[8.0]
def change
create_table :webhook_events do |t|
t.string :provider, null: false
t.string :event_id, null: false
t.string :event_type, null: false
t.text :payload, null: false # the raw body, exactly as received
t.datetime :received_at, null: false
t.datetime :processed_at
end
add_index :webhook_events, [:provider, :event_id], unique: true
end
end
# app/controllers/webhooks/stripe_controller.rb
class Webhooks::StripeController < ActionController::API
def create
payload = request.raw_post
event = Stripe::Webhook.construct_event(
payload, request.headers["Stripe-Signature"], ENV.fetch("STRIPE_WEBHOOK_SECRET")
)
result = WebhookEvent.insert(
{ provider: "stripe", event_id: event.id, event_type: event.type,
payload: payload, received_at: Time.current },
unique_by: [:provider, :event_id],
returning: [:id]
)
# An empty result means the row already existed: a duplicate delivery.
ProcessStripeEventJob.perform_later(result.rows.first.first) if result.rows.any?
head :ok
rescue JSON::ParserError, Stripe::SignatureVerificationError
head :bad_request
end
end
The controller does almost nothing on purpose. It checks the signature, stores the raw payload and answers at once, as Stripe asks.15 The real work happens in a background job, which can retry safely, and which looks up the payment's current state before changing the order. Background workers in Rails covers how to keep those jobs from failing quietly. For the data engineer, the table webhook_events is a gift: a complete, raw, timestamped record of everything the payment provider ever said, duplicates included, which a later chapter on loading data will use.
Files from partners have no contract, only habits
Files are still the most common way businesses exchange data. Wrenfield receives four kinds: the 3PL warehouse's daily CSV of shipments and returns, Stripe and PayPal settlement reports, supplier product feeds in CSV and XML, and exports from the newsletter tool. A 3PL, third party logistics, is the company that stores Wrenfield's stock and ships its parcels.
A file is a snapshot with no guarantees attached. Nobody promises the columns will stay in the same order, that the encoding will be declared, that a day will not be skipped, or that today's file will not quietly include yesterday's rows again. The partner wrote the export once, for their own purposes, and it does what it did on the day it was written. Each of Wrenfield's files has a known habit:
| File | Format | Habit that causes trouble |
|---|---|---|
| 3PL shipments and returns | CSV, semicolon delimited, Windows 1252 | Own SKU format with a WRF- prefix, local time with no zone, returns arrive up to 5 days late |
| Stripe settlement | CSV | Amounts net of fees, grouped by payout, so one payout covers many orders and many days |
| PayPal settlement | CSV | Its own transaction codes, fees and currency conversions as separate rows |
| Supplier A feed | XML | Dimensions in centimetres |
| Supplier B feed | CSV | Dimensions in millimetres, without saying so |
| Newsletter export | CSV | Email addresses with mixed case and stray spaces |
Example: one line of the warehouse file, read three ways
Here is the start of the 3PL file for 3 November, exactly as it lands (invented content, real behaviour):
despatch_time;order_ref;sku;qty;status;recipient;note
03/11/2026 09:14;R482915630;WRF-CUSH0412;2;DESPATCHED;Siobhán Ní Bhriain;
03/11/2026 09:20;R482915777;WRF-LAMP0088;1;DESPATCHED;Jürgen Groß;"Leave with neighbour; no 14"
25/10/2026 01:30;R481100245;WRF-THRW0031;1;RETURNED;Mark O'Neill;"Refund £24.00"
03/11/2026 09:31;R482915802;WRF-VASE0007;NA;DESPATCHED;Ana Nájera;
Read it the way a spreadsheet or a quick script would, with default settings, and three different things go wrong.
- The encoding. Python's pandas library assumes UTF 8 by default and stops at the first byte it cannot decode:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1. That byte is the á in Siobhán, written in Windows 1252. A tool that "helpfully" ignores errors would turn her into "Siobh?n" instead, which is worse, because nobody notices. - The types. Told the right encoding but nothing else, pandas guesses the column types. It reads "NA" in the quantity column as missing, because "NA" is on its list of default missing value markers,16 and so turns the whole quantity column into decimals: 2 becomes 2.0. That same list would turn Namibia's country code, NA, into a blank.
- The meaning. Even a perfect parse leaves
WRF-CUSH0412unjoinable to the shop's SKUCUSH0412, leaves 09:14 as a time in an unknown zone, and leaves a return from 25 October sitting in the 3 November file, nine days after the event.
The 25 October line hides a fourth trap. On that night the UK clocks went back at 2am, so 1.30am happened twice, once in British Summer Time and once in Greenwich Mean Time. A time written without a zone cannot say which. The next chapter, on types and formats, treats time zones in depth. Here it is enough to know that the file cannot answer the question, so the code has to.
Spreadsheets and manual entry carry a person's habits
Every business has a spreadsheet that matters more than it should. At Wrenfield it is the marketing cost sheet: influencer fees, a print run of flyers, the photographer, the trade show stand. Priya types it in by hand at the end of each month. It is the only record of every marketing cost that is not an ad platform bill, so it has to be in the data.
Spreadsheets mix data and presentation. A human reads a sheet with merged headers, a total row, a colour for "not yet paid" and a comment saying "tbc" without trouble. Code reads them as data. Typical findings in a hand kept sheet:
- Totals and subtotals stored as rows, so summing the column counts everything twice.
- A number typed as text ("£1.2k", "1,200 + VAT", "tbc").
- Months as words ("Oct", "October", "Oct 26") or as dates that Excel has silently converted to its own serial numbers.
- Meaning carried only by colour or by a comment.
- A new column inserted in March, so everything after it shifts.
Excel also has hard limits that a data pipeline does not share. A worksheet holds at most 1,048,576 rows and 16,384 columns, numbers keep 15 significant digits, and dates before 1 January 1900 are not available for calculation.17 A 16 digit card or tracking number typed into a cell as a number has its last digit replaced by a zero, without warning. What dirty data costs tells the documented stories of what happens when these limits meet real data.
Manual entry elsewhere follows the same pattern. Customers type their own addresses and phone numbers, so about 2% of Wrenfield's orders have a missing or invalid phone number. Staff type notes into the customer service tool, and the tool keeps whatever they type.
Example: turning Priya's sheet into rows
Priya's October block looks like this:
| Item | Cost | Paid |
|---|---|---|
| Influencer, Hannah (Leeds) | £1.2k | yes |
| Flyers, print run | 640 | yes |
| Photographer | tbc | no |
| Total | 1,840 |
A naive import gets one number wrong, one row wrong and one row missing. "£1.2k" is text, so it is dropped or read as zero. The total row is read as a fifth cost, so October's spend doubles to £3,680. The photographer has no number, so the row either disappears or becomes a zero cost, and the zero looks like a free photo shoot.
Callum does not try to make code understand the sheet. He changes the sheet. Priya now fills in a plain table on its own tab: one row per cost, a date column, a number column in pounds, a status column with two allowed values, no totals and no merged cells. The pretty summary lives on a second tab that the pipeline never reads. Fixing the source, when you can, beats any amount of clever cleaning, a principle that a later chapter on when to clean develops in full.
Scraped data comes with legal strings attached
Scraping means collecting data from other websites with a script, for example competitors' prices. It is tempting for a shop, and it is the dirtiest source of all: page layouts change without notice, prices appear with and without VAT, and a site that notices the scraper may serve it different content.
There is also the law. In the UK, a database can be protected by its own "database right", and extracting or reusing a substantial part of a protected database without permission infringes it.18 Across the EU the same right comes from the Database Directive.19 A website's terms may forbid scraping as well. And if scraped data includes anything about identifiable people, such as reviewers' names, UK data protection law applies in full, including the duty to tell people you hold their data even though you did not collect it from them.20 This is general information, not legal advice. If scraping is part of a plan, a solicitor should look at that specific plan first.
Example: a price check that stays on the right side
Priya wants to know whether her best selling throw is priced in line with the market. Callum's suggestion: rather than scraping whole competitor catalogues every night, check the 20 products that matter, by hand, once a month, and record the price, the date, the URL and whether VAT is included in Priya's sheet. Twenty rows a month is a few minutes' work, needs no scraper to maintain, copies no substantial part of anyone's database and contains no personal data. For this question, it answers everything a scraper would.
File formats, and what each one forgets to tell you
Every format is a set of promises about structure. The dirt lives in what the format does not promise. Here are the six that a shop's data arrives in.
CSV. Comma separated values: one record per line, fields separated by a delimiter. The closest thing to a standard is RFC 4180, and even that is "informational": it documents common practice and explicitly does not specify an Internet standard.21 Its rules are simple. Lines end with a carriage return and a line feed, a header line is optional, a field containing a comma, a double quote or a line break is wrapped in double quotes, and a double quote inside such a field is written twice. Spaces count as part of the field.21 What CSV does not carry is everything else: the encoding, the delimiter (many European exports use a semicolon because the comma is the decimal separator), whether there is a header, how missing values look and what type each column is. Every CSV file is a dialect, and the reader has to know which one.
JSON. JavaScript Object Notation, the format of most APIs. It does carry structure and a few types: strings, numbers, true, false, null, lists and objects. The standard, RFC 8259, requires UTF 8 for JSON exchanged between systems, forbids a byte order mark at the start of networked JSON, and warns that software only reliably handles numbers within the range and precision of a standard double, so very large ids can lose digits.22 It also says that names within an object should be unique and that software receiving duplicate names behaves unpredictably.22 JSON says nothing about which fields must be present, so a field that is missing today and present tomorrow is perfectly valid JSON.
XML. Extensible Markup Language, still common in supplier feeds and older systems. It is strict where CSV is loose: every XML processor must accept UTF 8 and UTF 16, a document can declare its own encoding in its first line, and a processor must stop normal processing at the first well formedness error.23 That strictness is a gift: a broken XML feed fails loudly. Its weak spot is that the same fact can live in an attribute or in an element, and namespaces make two identically named tags mean different things.
Excel. An .xlsx file is a zip archive of XML files. It stores values and formats separately, so a cell can hold 45231 and display "31/10/2023". What you see is not what is stored, and every reading library has to decide which of the two to give you.
Parquet. Apache Parquet is "an open source, column oriented data file format designed for efficient data storage and retrieval".24 Column oriented means all the values of one column are stored together, which compresses well and lets a query read only the columns it needs. A Parquet file carries its schema, so types travel with the data. It is the format you want to land data in, and rarely the format partners send.
Avro. Apache Avro stores data row by row, with its schema written in JSON. An Avro file includes the schema it was written with, and a reader can read the data into a different, newer schema under defined resolution rules.25 That makes Avro common in streaming systems such as Kafka, where producers and consumers change at different speeds.
Example: the same order line in four formats
Here is the first warehouse line from above, written as each format would carry it.
CSV (semicolon dialect, Windows 1252, no types):
03/11/2026 09:14;R482915630;WRF-CUSH0412;2;DESPATCHED;Siobhán Ní Bhriain;
{"despatch_time": "03/11/2026 09:14", "order_ref": "R482915630",
"sku": "WRF-CUSH0412", "qty": 2, "status": "DESPATCHED",
"recipient": "Siobhán Ní Bhriain", "note": null}
<?xml version="1.0" encoding="UTF-8"?>
<shipment order_ref="R482915630">
<despatch_time>03/11/2026 09:14</despatch_time>
<sku>WRF-CUSH0412</sku>
<qty>2</qty>
<recipient>Siobhán Ní Bhriain</recipient>
</shipment>
In CSV, 2 is text until you decide otherwise, and the empty note could mean "no note" or "note lost". In JSON, 2 is a number and the missing note is an explicit null. In XML, the encoding is declared and the order reference has become an attribute while everything else is an element, and the empty note has vanished entirely. In Parquet (not shown, it is binary), qty would be stored as an integer column and despatch_time could be a real timestamp type, if whoever wrote the file chose one. None of the four tells you that 09:14 is local time in the UK. That knowledge lives only in someone's head, or in your documentation.
Character encodings: why Seán becomes Seán
A computer stores text as bytes, numbers from 0 to 255. An encoding is the table that says which bytes mean which characters. When the writer and the reader use different tables, the text breaks in a very particular way, and once you recognise the pattern you can diagnose it at a glance.
Three encodings matter for a British, Irish, German or Austrian business.
- ASCII covers 128 characters: the English alphabet, digits and basic punctuation. No é, no ü, no £.
- Windows 1252 is the old Western European encoding on Windows. It uses one byte per character and fills the upper half of the table with accented letters and symbols: á is byte E1, ü is FC, ß is DF, £ is A3 and the euro sign is 80.26 Many older business systems, including Wrenfield's 3PL, still export in it.
- UTF 8 is the modern standard for Unicode, the catalogue that gives every character in every writing system its own number. It uses one byte for plain ASCII characters and two to four bytes for everything else.27 á becomes the two bytes C3 A1, ü becomes C3 BC, € becomes E2 82 AC.
Mojibake (a Japanese word for garbled characters) is what you get when UTF 8 bytes are read as Windows 1252: each multibyte character is shown as two or three Western European characters instead. The reverse mistake, Windows 1252 bytes read as UTF 8, usually fails outright, because a lone E1 byte is not valid UTF 8, or produces the replacement character � if the reader was told to carry on regardless.
Then there is the byte order mark, or BOM: the character U+FEFF placed at the very start of a file. In UTF 8 it is the three bytes EF BB BF. It is optional, it says nothing about byte order in UTF 8, and its only use is as a signature that the file is UTF 8.28 Excel often writes it when saving "CSV UTF 8". A reader that does not expect it sees an invisible character glued to the first column name, so a column called despatch_time is actually despatch_time and every lookup by name fails. In Python, the utf-8-sig codec reads UTF 8 and removes a leading BOM if there is one.29
Example: four names, byte by byte
Here is what happens to four strings from Wrenfield's data when the bytes are UTF 8 but the reader assumes Windows 1252, and the other way round. Every row below was produced by actually running the conversion.
| Original | UTF 8 bytes | Read as Windows 1252 | Windows 1252 bytes read as UTF 8 |
|---|---|---|---|
| Seán | 53 65 C3 A1 6E | Seán | Se�n |
| Siobhán | ... 68 C3 A1 6E | Siobhán | Siobh�n |
| Müller | 4D C3 BC 6C 6C 65 72 | Müller | M�ller |
| Straße | ... 61 C3 9F 65 | Straße | Stra�e |
| £24.00 | C2 A3 32 34 ... | £24.00 | �24.00 |
Walk through the first row. The á in Seán is Unicode character U+00E1. In UTF 8 that becomes two bytes, C3 and A1. A reader using Windows 1252 looks up each byte separately: C3 is à and A1 is ¡.26 So one letter becomes two, and Seán becomes Seán. The ß in Straße goes the same way: C3 9F becomes à and Ÿ.
The pattern is the diagnosis. If you see à followed by another character where an accented letter should be, the data is UTF 8 that was read as Windows 1252, and you can fix it by reading the original bytes again with the right encoding. If you see �, the original byte is already gone, replaced at read time, and the only fix is to go back to the source file. That is the strongest argument in this chapter for keeping every source file exactly as it arrived.
Names are where encoding errors hurt most, because they are personal. A customer called Seán, Siobhán, Jürgen or Ana Nájera who receives an email addressed to "Dear Seán" notices, and is entitled to. Accuracy of personal data is a legal principle under UK GDPR as well as courtesy, a point the previous chapter covers.
Why data is born dirty
Look back over the sources and the same six causes keep appearing. They are worth naming, because each one suggests where to look first.
| Cause | What happens | Wrenfield example |
|---|---|---|
| Human entry | People type what they mean, not what the system needs | 2% invalid phone numbers, "tbc" in the cost sheet, country typed as "England" |
| System changes | Old rows keep the rules of the system that wrote them | Float prices from the legacy import |
| Integrations | Two systems describe the same thing in their own codes | 3PL SKU WRF-CUSH0412 against shop SKU CUSH0412 |
| Time zones | Clocks without zones, servers in different places | 3PL local time against shop UTC |
| Defaults | An empty field gets filled with something plausible | A missing weight saved as 0, a missing date as 1 January 1970 |
| Version changes | An API or export changes shape over time | A new field in an ad platform's API version, Supplier B switches from cm to mm |
There is a seventh, quieter cause: meaning drift. The data stays the same shape while what it means changes. Wrenfield started offering click and collect in 2024, so "shipped" orders after that date include parcels nobody shipped. No validation rule catches this, because every value is still valid. Only knowing the business does.
Example: the first audit
When Callum first audited Wrenfield's data, he logged every distinct problem he found, with its source and its type. He found 64 (all invented for this series, but typical in their mix). The two charts below show where they came from and what kind they were.
Two things stand out. Half of all problems (32 of 64: the 3PL file, the supplier feeds and the payment files) come from files exchanged with partners, which are exactly the sources nobody at Wrenfield controls. And the problem types are spread fairly evenly: no single kind of fix would have cleaned more than a fifth of them. That is normal. It is also why a later chapter on profiling starts by measuring all of them before fixing any.
Reading a partner's CSV properly, in Python
Now the practical part: reading the 3PL file so that nothing is guessed. The approach has two stages, and the split is the important idea.
- Land it as text. Read every column as a string, with the delimiter and encoding stated explicitly and no automatic conversion of missing values. This stage cannot lose information, so it cannot go wrong quietly.
- Type it on purpose. Convert each column with an explicit rule: a stated date format, a stated time zone, a stated way to handle values that do not convert. Anything that fails a rule becomes a visible gap you can count, never a silent guess.
Example: the 3PL file in pandas
This is pandas 3, and every parameter used is documented in its read_csv reference.16
# Python, pandas 3: read the 3PL file without letting anything be guessed
import pandas as pd
raw = pd.read_csv(
"shipments_20261103.csv",
sep=";", # the 3PL uses semicolons
encoding="cp1252", # Windows 1252, as the 3PL confirmed in writing
dtype=str, # every column as text: nothing converted yet
keep_default_na=False, # "NA" stays "NA", an empty field stays ""
on_bad_lines="error", # a row with too many fields stops the load
)
clean = pd.DataFrame({
"order_number": raw["order_ref"].str.strip(),
"sku": raw["sku"].str.strip().str.removeprefix("WRF-"),
"quantity": pd.to_numeric(raw["qty"], errors="coerce").astype("Int64"),
"status": raw["status"].str.strip().str.lower(),
"despatched_at_utc": (
pd.to_datetime(raw["despatch_time"], format="%d/%m/%Y %H:%M")
.dt.tz_localize("Europe/London", ambiguous="NaT", nonexistent="NaT")
.dt.tz_convert("UTC")
),
})
problems = clean[clean["quantity"].isna() | clean["despatched_at_utc"].isna()]
print(clean)
print(problems[["order_number"]])
Line by line: dtype=str and keep_default_na=False make stage one lossless. removeprefix maps the 3PL's SKU to the shop's. to_numeric(..., errors="coerce") turns anything that is not a number into a gap, and Int64 (with a capital I) is pandas' whole number type that allows gaps, so 2 stays 2 and does not become 2.0. The date is parsed with a stated format, so 03/11 can only mean 3 November. Then tz_localize says "these clock times are UK local time", and ambiguous="NaT" turns the impossible to decide 1.30am on 25 October into a gap instead of a guess. The output:
order_number sku quantity status despatched_at_utc
0 R482915630 CUSH0412 2 despatched 2026-11-03 09:14:00+00:00
1 R482915777 LAMP0088 1 despatched 2026-11-03 09:20:00+00:00
2 R481100245 THRW0031 1 returned NaT
3 R482915802 VASE0007 <NA> despatched 2026-11-03 09:31:00+00:00
order_number
2 R481100245
3 R482915802
Two rows out of four need a human decision, and the code says which ones. In November, 9.14am in Leeds is 09:14 UTC, because the UK is on Greenwich Mean Time. In July the same clock time would convert to 08:14 UTC.
Example: the same file in polars
Polars is a newer DataFrame library that is often much faster on large files. Its read_csv defaults to UTF 8,30 so the simplest dependable route is to decode the bytes yourself and hand polars clean UTF 8. infer_schema=False reads every column as text, the same lossless first stage.30
# Python, polars: decode explicitly, read as text, then type on purpose
import polars as pl
with open("shipments_20261103.csv", "rb") as f:
text = f.read().decode("cp1252")
raw = pl.read_csv(text.encode("utf-8"), separator=";", infer_schema=False)
clean = raw.select(
pl.col("order_ref").str.strip_chars().alias("order_number"),
pl.col("sku").str.strip_chars().str.strip_prefix("WRF-").alias("sku"),
pl.col("qty").cast(pl.Int32, strict=False).alias("quantity"),
pl.col("despatch_time")
.str.to_datetime("%d/%m/%Y %H:%M")
.dt.replace_time_zone("Europe/London", ambiguous="null", non_existent="null")
.dt.convert_time_zone("UTC")
.alias("despatched_at_utc"),
)
print(clean)
The result matches the pandas version row for row: the ambiguous return gets a null time and "NA" gets a null quantity. .decode("cp1252") will raise an error if the file contains a byte that Windows 1252 does not define, which is exactly the behaviour you want when a partner silently switches encodings.
Reading the same file in PostgreSQL with COPY
For many smaller shops, PostgreSQL alone is the honest choice of warehouse. Its COPY command loads files fast and supports the same two stage approach. Stage one is a raw table where every column is text, plus two columns that record where each row came from and when.
Example: landing and typing the 3PL file in PostgreSQL
-- PostgreSQL: stage one, a raw table that cannot reject anything
CREATE SCHEMA IF NOT EXISTS raw_3pl;
CREATE TABLE raw_3pl.shipments (
despatch_time text,
order_ref text,
sku text,
qty text,
status text,
recipient text,
note text,
_source_file text,
_loaded_at timestamptz NOT NULL DEFAULT now()
);
-- psql: load the file from the machine you are on (one line, as psql requires)
\copy raw_3pl.shipments (despatch_time, order_ref, sku, qty, status, recipient, note) FROM 'shipments_20261103.csv' WITH (FORMAT csv, DELIMITER ';', HEADER true, ENCODING 'WIN1252')
UPDATE raw_3pl.shipments
SET _source_file = 'shipments_20261103.csv'
WHERE _source_file IS NULL;
ENCODING 'WIN1252' tells PostgreSQL what the file's bytes mean, and it converts them into the database's own encoding as it loads. FORMAT csv switches on proper handling of quoted fields, so the quoted delivery note stays one field despite the semicolon inside it. In CSV format an unquoted empty field becomes NULL by default.31 And \copy is the psql client's command: it reads the file from your own machine, whereas plain COPY ... FROM 'file' asks the database server to read a file on the server, which needs special privileges.31
-- PostgreSQL: stage two, type every column on purpose
SET TIME ZONE 'UTC';
SELECT
trim(order_ref) AS order_number,
regexp_replace(trim(sku), '^WRF-', '') AS sku,
CASE WHEN qty ~ '^\d+$' THEN qty::integer END AS quantity,
lower(trim(status)) AS status,
to_timestamp(despatch_time, 'DD/MM/YYYY HH24:MI')::timestamp
AT TIME ZONE 'Europe/London' AS despatched_at
FROM raw_3pl.shipments;
order_number | sku | quantity | status | despatched_at
--------------+----------+----------+------------+------------------------
R482915630 | CUSH0412 | 2 | despatched | 2026-11-03 09:14:00+00
R482915777 | LAMP0088 | 1 | despatched | 2026-11-03 09:20:00+00
R481100245 | THRW0031 | 1 | returned | 2026-10-25 01:30:00+00
R482915802 | VASE0007 | | despatched | 2026-11-03 09:31:00+00
Look closely at the third row, because it is the most useful thing in this section. pandas and polars refused to guess the ambiguous 1.30am. PostgreSQL did not refuse: it picked one of the two possible moments (here the later one, in Greenwich Mean Time) and gave no warning. Neither behaviour is wrong, but you must know which one your tool has. If the exact minute of a return matters, flag times that fall in the hour the clocks go back before converting them.
The CASE WHEN qty ~ '^\d+$' line is a regular expression check: convert the quantity only if it is made of digits, otherwise leave it NULL. PostgreSQL 17 and later can also skip unconvertible rows during COPY itself with the ON_ERROR ignore option.31 I prefer loading text and converting afterwards, because then the rejected rows are still in the raw table where someone can look at them, rather than gone.
A file that arrives should go through one gate
Everything above can be turned into one routine that every incoming file goes through, whatever its source. The point is that a file either passes every check and moves on, or it stops in a quarantine area with a reason, and somebody is told. It never half loads.
The 0.5% threshold is a choice, not a law. For the 3PL file Callum set it at 0.5% because a normal day has 60 to 70 lines and one or two odd ones, while a broken export breaks most of them. For a payment file the right threshold is zero.
Example: the morning the 3PL changed its export
In this invented scenario, one Monday the 3PL upgrades its warehouse software. The new export is UTF 8 with a BOM and has a new column, carrier, inserted after sku. Without the gate, a script reading by position would put the carrier name into the quantity column, convert "DPD" to a gap, and report that Wrenfield shipped nothing that day. With the gate, the header check fails at step d (the first column name now carries the invisible BOM, and carrier is unexpected), the file goes to quarantine, and Callum gets a message at 7am saying exactly why. He updates the expected header, switches the encoding to utf-8-sig, and reprocesses the archived file. Nothing downstream ever saw a wrong number.
Keep a register of every source
The last practical habit of this chapter costs an hour and pays for itself the first time something changes. Write down every source in one table: what it is, who owns it, how it arrives, how often, in what format and encoding, which time zone its timestamps are in, and what you already know is wrong with it. Most of what this chapter calls dirt is not random. It is a known habit of a known source, and a habit you have written down stops being a surprise.
Example: Wrenfield's source register
| Source | Owner | Arrives as | When | Format and encoding | Time zone | Known issues |
|---|---|---|---|---|---|---|
| Solidus database | Callum | Nightly copy | 2am | PostgreSQL tables | UTC | Legacy float prices, free text countries, 3.1% duplicate accounts, about 40 test orders a year |
| GA4 export | Callum | BigQuery tables | Daily, revised for up to 3 days | Nested events | UTC (microseconds) | About 15% of purchases missing |
| Google Ads | Priya (account), Callum (API) | API, last 30 days nightly | 3am | JSON, money in micros | Account time zone | Conversions dated to click |
| Meta Ads | Priya, Callum | API, last 30 days nightly | 3am | JSON | Ad account time zone | Rate limited per ad account |
| Stripe | Callum | Webhooks plus a daily payout report | Continuous and daily | JSON and CSV | Unix seconds, UTC | Duplicates and disorder in webhooks, net amounts in payouts |
| PayPal | Priya | Settlement report | Daily | CSV | Stated in the file | Fees and conversions as separate rows |
| 3PL shipments and returns | The 3PL's account manager | CSV by secure file transfer (SFTP) | 6am | Semicolons, Windows 1252 | UK local, no zone | WRF- SKU prefix, returns up to 5 days late |
| Supplier feeds | Each supplier | CSV and XML by URL | Weekly | Mixed | None | Supplier B in mm, the rest in cm |
| Newsletter tool | Priya | Export | Weekly | CSV, UTF 8 | Tool's own | Mixed case emails, stray spaces |
| Service tickets | Priya | API | Daily | JSON | UTC | Free text categories |
| Marketing cost sheet | Priya | Spreadsheet tab | Monthly | Google Sheet | None | Hand typed, fixed to a plain table in November |
That table is also the first draft of something later chapters build properly: a data contract with each source, and a catalogue of what the business's data means.
Conclusion
Raw data is never clean because it was never meant for you. Each source was built to run one part of the business and records the world the way that part needs. The shop database keeps the present and overwrites the past. APIs hand data over in pages, under rate limits, in units and dates of their own choosing. Analytics exports see only the visitors who let them and keep revising recent days. Webhooks arrive twice, late and out of order. Partner files carry habits instead of contracts. Spreadsheets carry a person's habits. And underneath all of it, bytes only become letters if writer and reader agree on the encoding.
None of that is a reason for despair. It is a reason for two habits that the rest of this series builds on. First, keep every source exactly as it arrived, because you can always clean again from the original and never from a damaged copy. Second, never let a tool guess: state the delimiter, the encoding, the types, the date format and the time zone, and turn everything that does not fit into a visible, countable gap. The next chapter goes one level deeper, into the data types themselves and why a number, a date or an empty field can quietly break a pipeline.
