Skip to main content

Testing and QA · Advanced · 24 min

Anonymise production data before using it in test environments

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7 (PGDG apt) · pgcrypto

You will turn a PostgreSQL 18 production dump into a masked copy for staging, with keyed pseudonyms that keep joins working, coarser dates and amounts, no free text, and two scans that show no emails, phone numbers or original values slipped through.

On this page

Copying production into staging is the quickest way to get realistic test data, and the quickest way to leak it. Staging has more people with access, weaker logging, shared passwords and screenshots pasted into bug trackers. Every customer in that copy is still a real person, and data protection law such as the EU GDPR or Nigeria's Data Protection Act 2023 still applies to them.

In this tutorial you take a PostgreSQL 18 dump, restore it on a private masking machine, and change it until it is safe enough to hand to testers. You write down a decision for every column, replace emails and names with keyed pseudonyms that still join across tables, make dates and amounts coarser, shuffle cities, remove free text, and then scan the result for anything that looks like an email or phone number, or matches an original value.

One thing to be clear about from the start: this is masking, not full anonymisation. The result is pseudonymised data. Whoever holds the key can link a pseudonym back to a known email, and the remaining rows (order patterns, city, birth year) can still single someone out when combined. Under the GDPR (Recital 26), pseudonymised data is still personal data. Masking lowers the risk a lot; it does not remove the duty to protect the copy.

Step 1 · Decide whether you need production data at all

Before you copy anything, ask what the test needs. Most tests do not need production data:

  • Unit and integration tests need small, known data that you build in the test with factories. That data is never personal, and the test says exactly what it depends on.
  • Demo and training environments need data that looks real. Generated names and addresses are enough.
  • Performance tests need the right volume and shape: row counts, how many orders a typical customer has, how skewed the data is. You can often generate this from a few counts taken from production.

Masked production data earns its place when the bug or the risk lives in the real data: a migration that must survive ten years of odd rows, a report that only breaks on real distributions, or a support case you cannot reproduce. Even then, ask whether a subset (one month, one region) is enough.

Write the reason down, with who approved it and how long the masked copy may live. If your team is in Nigeria, the NDPA expects you to be able to explain why you process personal data; the same note answers that question.

Check it worked

You have a short written note that names the test or bug that needs production-shaped data, why generated data is not enough, who approved the copy and when it will be deleted. If you cannot fill in the first line, stop here and use factories instead.

Step 2 · Set up a private masking workspace

Masking happens on a machine with the same protection as production, never on staging. The raw dump only ever lives there. In this tutorial one PostgreSQL server plays all three parts, using three database names: shop_prod, shop_mask and shop_staging.

Give your own login a PostgreSQL role that can create databases, so you can work without the postgres superuser. Skip this if you already have one:

Bash
sudo -u postgres createuser --createdb "$(whoami)"

Create a private folder and a masking key. The key is what makes the pseudonyms impossible to recompute without it, so it is a secret. Create the file private from the start:

Bash
mkdir -m 700 ~/mask-demo
(umask 077; openssl rand -hex 32 > ~/mask-demo/mask.key)
ls -l ~/mask-demo/mask.key

Keep the key in your team's secrets manager, never in the repository and never on staging. If you reuse the same key each month, a customer gets the same pseudonym every time, which keeps testers' saved searches working. If you do not need that, make a new key each time and destroy it afterwards.

To practise, create a small stand-in for production. If you have a real dump, skip this block and copy your dump to ~/mask-demo/prod.dump instead. The rows below are invented:

Bash
createdb shop_prod
psql -X -v ON_ERROR_STOP=1 -q -d shop_prod <<'SQL'
CREATE TABLE customers (
  id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  full_name text NOT NULL,
  email text NOT NULL UNIQUE,
  phone text,
  date_of_birth date,
  city text NOT NULL,
  created_at timestamptz NOT NULL
);
CREATE TABLE orders (
  id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  customer_id integer NOT NULL REFERENCES customers (id),
  total_cents integer NOT NULL,
  placed_at timestamptz NOT NULL,
  delivery_note text
);
CREATE TABLE newsletter_signups (
  email text PRIMARY KEY,
  signed_up_at timestamptz NOT NULL
);
CREATE TABLE support_tickets (
  id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  customer_id integer NOT NULL REFERENCES customers (id),
  body text NOT NULL,
  opened_at timestamptz NOT NULL
);

INSERT INTO customers (full_name, email, phone, date_of_birth, city, created_at) VALUES
  ('Adaeze Okafor', 'Adaeze.Okafor@example.com', '+234 803 555 0142', '1991-04-17', 'Lagos',   '2025-10-06 08:12+00'),
  ('Kwame Mensah',  'kwame.mensah@example.net',  '+233 24 555 0187',  '1985-11-02', 'Accra',   '2025-10-11 14:40+00'),
  ('Wanjiru Kamau', 'wanjiru.kamau@example.org', '+254 712 555 019',  '1979-06-30', 'Nairobi', '2025-10-16 19:05+00'),
  ('Tunde Bakare',  'tunde.bakare@example.com',  '0803 555 0199',     '2001-01-09', 'Lagos',   '2025-10-21 07:30+00'),
  ('Fatima Bello',  'fatima.bello@example.com',  NULL,                '1996-08-21', 'Abuja',   '2025-10-26 11:55+00'),
  ('Oliver Grant',  'oliver.grant@example.co.uk','+44 20 7946 0958',  '1968-03-05', 'London',  '2025-10-31 16:20+00');

INSERT INTO orders (customer_id, total_cents, placed_at, delivery_note)
SELECT (g % 6) + 1,
       1500 + (g * 737) % 20000,
       timestamptz '2026-01-05 09:00+00' + g * interval '2 days 3 hours',
       CASE WHEN g % 10 = 0 THEN 'Call 0803 555 0142 at the gate' END
FROM generate_series(1, 60) AS g;

INSERT INTO newsletter_signups (email, signed_up_at) VALUES
  ('adaeze.okafor@example.com', '2025-11-02 10:00+00'),
  ('KWAME.MENSAH@example.net',  '2025-11-09 21:15+00'),
  ('fatima.bello@example.com',  '2025-12-01 06:45+00'),
  ('ngozi.eze@example.com',     '2026-01-14 13:30+00');

INSERT INTO support_tickets (customer_id, body, opened_at) VALUES
  (2, 'Please send the receipt to kwame.m@example.net instead of my main address.', '2026-02-03 09:10+00'),
  (4, 'Delivery rider could not find me. My other number is 0809 555 0123.',        '2026-02-11 17:42+00'),
  (1, 'Wrong size, I want to swap it for a larger one.',                             '2026-03-01 12:00+00');
SQL
(umask 077; pg_dump -Fc shop_prod > ~/mask-demo/prod.dump)

Check it worked

Bash
ls -l ~/mask-demo

The folder holds mask.key and prod.dump, both with mode -rw-------, so only you can read them.

Step 3 · Restore the dump into a masking database

Restore into a database whose only job is to be masked. You will throw it away at the end.

Bash
createdb shop_mask
pg_restore --no-owner --no-privileges --exit-on-error -d shop_mask ~/mask-demo/prod.dump

--no-owner and --no-privileges drop production's ownership and GRANT lines, so the objects belong to you and no production role names leak into the copy. --exit-on-error stops at the first problem, so a half-restored database cannot be masked by mistake.

Save a plain-text dump of the unmasked copy for the scanner test in a later step, and a list of the original identifying values to check against at the end. Both hold personal data, so create them private:

Bash
(umask 077
 pg_dump shop_mask > ~/mask-demo/before.sql
 psql -X -At -d shop_mask -c "
   SELECT full_name FROM customers
   UNION SELECT email FROM customers
   UNION SELECT phone FROM customers WHERE phone IS NOT NULL
   UNION SELECT email FROM newsletter_signups" > ~/mask-demo/known-values.txt)

Check it worked

Bash
psql -X -At -d shop_mask -c "SELECT count(*) FROM customers" -c "SELECT count(*) FROM orders"
wc -l < ~/mask-demo/known-values.txt

You see 6 and 60, the same counts as production, then 20: six names, six customer emails, five phone numbers and three of the four newsletter emails: two differ from a customer's only in letter case, so UNION keeps them, ngozi.eze@example.com belongs to no customer, and fatima.bello@example.com matches a customer exactly, so it is removed as a duplicate. With your own dump the numbers are your own; the point is that the counts match the source.

Step 4 · Write a column inventory and check it

Masking fails quietly when someone adds a column next month and nobody decides what to do with it. Keep an inventory: one line per column with the action you will take. The actions used here are:

  • keep: not personal (surrogate ids, foreign keys).
  • pseudonymise: replace with a keyed pseudonym that stays the same everywhere it appears.
  • generalise: make coarser (birth date to year, timestamp to day or month, amount to the nearest 5.00).
  • shift: move dates by an amount that depends on the customer, so each customer's history keeps its order.
  • shuffle: keep the values but move them between rows, which keeps the overall mix and breaks the link to a person.
  • remove: drop the value or replace it with filler.
Bash
cat > ~/mask-demo/inventory.csv <<'CSV'
customers,id,keep
customers,full_name,pseudonymise
customers,email,pseudonymise
customers,phone,remove
customers,date_of_birth,generalise
customers,city,shuffle
customers,created_at,generalise
orders,id,keep
orders,customer_id,keep
orders,total_cents,generalise
orders,placed_at,shift
orders,delivery_note,remove
newsletter_signups,email,pseudonymise
newsletter_signups,signed_up_at,generalise
support_tickets,id,keep
support_tickets,customer_id,keep
support_tickets,body,remove
support_tickets,opened_at,generalise
CSV

Now a script that compares the inventory with the columns the database actually has, and fails if any column is missing a decision:

Bash
cat > ~/mask-demo/check-inventory.sh <<'SCRIPT'
#!/bin/bash
set -euo pipefail
db="${1:?usage: check-inventory.sh <database>}"
dir="$(dirname "$0")"

columns="$(psql -X -At -d "$db" -c "
  SELECT table_name || ',' || column_name
  FROM information_schema.columns
  WHERE table_schema = 'public'" | LC_ALL=C sort)"
decided="$(cut -d, -f1,2 "$dir/inventory.csv" | LC_ALL=C sort)"

missing="$(LC_ALL=C comm -23 <(echo "$columns") <(echo "$decided"))"
if [ -n "$missing" ]; then
  echo "Columns with no masking decision:"
  echo "$missing"
  exit 1
fi
echo "All $(echo "$columns" | wc -l) columns have a masking decision."
SCRIPT
chmod 700 ~/mask-demo/check-inventory.sh
~/mask-demo/check-inventory.sh shop_mask

Check it worked

The script prints All 18 columns have a masking decision. Now see it catch a new column. Add one, run the check, then remove the column again:

Bash
psql -X -q -d shop_mask -c "ALTER TABLE customers ADD COLUMN referral_code text"
~/mask-demo/check-inventory.sh shop_mask || echo "Inventory check failed"
Bash
psql -X -q -d shop_mask -c "ALTER TABLE customers DROP COLUMN referral_code"

The check lists customers,referral_code under "Columns with no masking decision:" and you see Inventory check failed. Run this check first in every masking run, so a schema change stops the pipeline instead of shipping an unmasked column.

Step 5 · Build a scanner and prove it finds personal data

You need a way to check the output that does not trust the masking script. This scanner reads a plain SQL dump and reports anything shaped like an email address (other than the @example.invalid pseudonyms you will create) or a phone number in international (+234 803 ...) or local (0803 ...) form. .invalid is a reserved domain that never resolves, so a pseudonymous email can never reach a real inbox.

Bash
cat > ~/mask-demo/scan-pii.sh <<'SCRIPT'
#!/bin/bash
set -euo pipefail
file="${1:?usage: scan-pii.sh <plain SQL dump>}"

email='[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}'
phone_intl='\+[0-9]{1,3}([ -]?[0-9]{2,4}){3}'
phone_local='\b0[0-9]{3}[ -]?[0-9]{3}[ -]?[0-9]{4}\b'

hits="$( {
  grep -Eo "$email" "$file" | grep -v '@example\.invalid$' || true
  grep -Eo "$phone_intl|$phone_local" "$file" || true
} | sort | uniq -c)"

if [ -n "$hits" ]; then
  echo "Possible personal data in $file:"
  echo "$hits"
  exit 1
fi
echo "No email or phone patterns found in $file."
SCRIPT
chmod 700 ~/mask-demo/scan-pii.sh

A scanner you have never seen fail proves nothing. Run it on the unmasked dump:

Bash
~/mask-demo/scan-pii.sh ~/mask-demo/before.sql || echo "Scan found personal data"

Check it worked

The scanner lists every customer email, the phone numbers, the address kwame.m@example.net hidden inside a support ticket and 0809 555 0123 inside another ticket, then prints Scan found personal data. The ticket hits matter: they are in no column you would think of as "the email column".

Patterns only find what has a pattern. They miss names, street addresses and anything written in a way you did not expect. That is why free text is removed in a later step rather than scrubbed, and why the final step also checks for the exact original values.

Step 6 · Replace identifiers with keyed pseudonyms

A plain hash such as SHA-256 of an email is not enough: anyone with a list of likely emails can hash them and match. An HMAC mixes in your secret key, so without the key nobody can recompute a pseudonym. Because the same input and key always give the same output, an email gets the same pseudonym in every table, and joins on email keep working.

Normalise before hashing. Adaeze.Okafor@example.com in customers and adaeze.okafor@example.com in newsletter_signups are the same person, so lower-case and trim them first. See how many newsletter sign-ups match a customer today:

Bash
psql -X -At -d shop_mask -c "
  SELECT count(*) FROM customers c
  JOIN newsletter_signups n ON lower(trim(n.email)) = lower(trim(c.email))"

The answer is 3. Remember it.

Write the masking script. It reads the key from the MASK_KEY environment variable with psql's \getenv, so the key is never typed on a command line or saved in the script, and it stops before touching anything if the variable is missing. Everything runs in one transaction, so a failure leaves the database unmasked rather than half masked.

Bash
cat > ~/mask-demo/mask.sql <<'SQL'
\set ON_ERROR_STOP on
\getenv mask_key MASK_KEY
\if :{?mask_key}
\else
  DO $$ BEGIN RAISE EXCEPTION 'MASK_KEY is not set'; END $$;
\endif

BEGIN;
CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- Keyed pseudonym: same input and key, same output; unreadable without the key.
CREATE FUNCTION pg_temp.pseudo(value text, key text) RETURNS text
LANGUAGE sql IMMUTABLE
AS $$ SELECT encode(hmac(lower(trim(value)), key, 'sha256'), 'hex') $$;

-- Identifiers
UPDATE customers SET
  full_name = 'Customer ' || upper(left(pg_temp.pseudo(email, :'mask_key'), 6)),
  email     = 'user_' || left(pg_temp.pseudo(email, :'mask_key'), 16) || '@example.invalid',
  phone     = NULL;

UPDATE newsletter_signups SET
  email = 'user_' || left(pg_temp.pseudo(email, :'mask_key'), 16) || '@example.invalid';

-- MASK_REST_PLACEHOLDER

DROP EXTENSION pgcrypto;
COMMIT;
SQL

The full name is replaced with a label made from the email pseudonym, so testers can still tell customers apart. The phone column is emptied; if your app's forms need a phone number to work, set every row to one agreed test number and add it to the scanner's allowed list.

The placeholder comment marks where the next step's statements go. Run the script now on the identifiers alone:

Bash
MASK_KEY="$(cat ~/mask-demo/mask.key)" psql -X -q -d shop_mask -f ~/mask-demo/mask.sql

Run it on a fresh restore only. Running it twice hashes the pseudonyms again, and they no longer match last month's copy.

Check it worked

Bash
psql -X -d shop_mask -c "SELECT id, full_name, email, phone FROM customers ORDER BY id"
psql -X -At -d shop_mask -c "
  SELECT count(*) FROM customers c JOIN newsletter_signups n ON n.email = c.email"

Every name is Customer plus six hex characters, every email is user_<16 hex characters>@example.invalid, and every phone is empty. The join now uses plain equality and still returns 3: the mixed-case and upper-case addresses became the same pseudonym as their customer.

Step 7 · Generalise dates and amounts, shuffle and remove the rest

Identifiers are only half the problem. A birth date, a home city and the exact time and value of each order can point at one person even with the name gone. Make each of these coarser, but keep what tests rely on: totals in the right range, each customer's orders in the right sequence, the real mix of cities.

Start again from a clean copy, because the script must run once on unmasked data:

Bash
dropdb shop_mask
createdb shop_mask
pg_restore --no-owner --no-privileges --exit-on-error -d shop_mask ~/mask-demo/prod.dump

Now write the full masking script. It is the same as before, with the remaining statements where the placeholder was:

Bash
cat > ~/mask-demo/mask.sql <<'SQL'
\set ON_ERROR_STOP on
\getenv mask_key MASK_KEY
\if :{?mask_key}
\else
  DO $$ BEGIN RAISE EXCEPTION 'MASK_KEY is not set'; END $$;
\endif

BEGIN;
CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- Keyed pseudonym: same input and key, same output; unreadable without the key.
CREATE FUNCTION pg_temp.pseudo(value text, key text) RETURNS text
LANGUAGE sql IMMUTABLE
AS $$ SELECT encode(hmac(lower(trim(value)), key, 'sha256'), 'hex') $$;

-- Identifiers
UPDATE customers SET
  full_name = 'Customer ' || upper(left(pg_temp.pseudo(email, :'mask_key'), 6)),
  email     = 'user_' || left(pg_temp.pseudo(email, :'mask_key'), 16) || '@example.invalid',
  phone     = NULL;

UPDATE newsletter_signups SET
  email = 'user_' || left(pg_temp.pseudo(email, :'mask_key'), 16) || '@example.invalid';

-- Generalise: birth date to 1 January of the year, sign-up times to the month or day.
UPDATE customers SET
  date_of_birth = date_trunc('year', date_of_birth)::date,
  created_at    = date_trunc('month', created_at);
UPDATE newsletter_signups SET signed_up_at = date_trunc('day', signed_up_at);
UPDATE support_tickets    SET opened_at    = date_trunc('day', opened_at);

-- Amounts to the nearest 500 cents (5.00).
UPDATE orders SET total_cents = round(total_cents / 500.0)::integer * 500;

-- Shift every order of a customer by the same number of days, -15 to +15,
-- taken from the keyed hash of the customer id. Order within a customer is kept.
UPDATE orders SET placed_at = placed_at
  + make_interval(days => get_byte(hmac(customer_id::text, :'mask_key', 'sha256'), 0) % 31 - 15);

-- Shuffle cities between customers: the same mix, no longer tied to a person.
WITH shuffled AS (
  SELECT city, row_number() OVER (ORDER BY random()) AS rn FROM customers
), slots AS (
  SELECT id, row_number() OVER (ORDER BY id) AS rn FROM customers
)
UPDATE customers c SET city = shuffled.city
FROM slots JOIN shuffled USING (rn)
WHERE c.id = slots.id;

-- Free text: replace with filler of the same length, so layouts are still tested.
UPDATE orders SET delivery_note = rpad('[removed] ', length(delivery_note), 'x ')
  WHERE delivery_note IS NOT NULL;
UPDATE support_tickets SET body = rpad('[removed] ', length(body), 'x ');

DROP EXTENSION pgcrypto;
COMMIT;
SQL
~/mask-demo/check-inventory.sh shop_mask
MASK_KEY="$(cat ~/mask-demo/mask.key)" psql -X -q -d shop_mask -f ~/mask-demo/mask.sql

Free text is replaced, not scrubbed. Notes and tickets hold names, addresses, phone numbers written as words, and health or family details, often in more than one language: a Lagos customer may write in English, Pidgin and Yoruba in one message, and no regex list covers that. Filler of the same length keeps the cases testers care about, such as a 2,000-character note breaking a layout on a small Android screen, without keeping the words.

The shuffle uses random(), so it comes out differently on every run. That is intended: a fixed seed would let anyone with the script undo it.

Check it worked

Compare the masked copy with production. Row counts, cities and order sequences should match; exact values should not:

Bash
for db in shop_prod shop_mask; do
  echo "$db:"
  psql -X -At -d "$db" -c "SELECT string_agg(city || '=' || n, ' ' ORDER BY city) FROM (SELECT city, count(*) AS n FROM customers GROUP BY city) t"
  psql -X -At -d "$db" -c "SELECT count(*), sum(total_cents) FROM orders"
done
psql -X -d shop_mask -c "SELECT id, date_of_birth, city, created_at FROM customers ORDER BY id"
psql -X -d shop_mask -c "SELECT id, body FROM support_tickets ORDER BY id"

Both databases show Abuja=1 Accra=1 Lagos=2 London=1 Nairobi=1, and both have 60 orders, with order totals that differ by a few per cent at most. Birth dates all end in -01-01, created_at falls on the first of a month, and each ticket body starts with [removed] followed by x x x.

Step 8 · Scan, dump and hand over the masked copy

Make the dump you will ship, then scan that exact file. Scanning the database instead would check something other than what leaves the machine. pg_restore -f turns the archive back into plain SQL for the scanner without restoring anything:

Bash
pg_dump -Fc shop_mask > ~/mask-demo/masked.dump
pg_restore -f ~/mask-demo/masked.sql ~/mask-demo/masked.dump
~/mask-demo/scan-pii.sh ~/mask-demo/masked.sql

The scanner prints No email or phone patterns found. Now check for the exact original values, which also covers the names the pattern scan cannot see:

Bash
if grep -F -i -q -f ~/mask-demo/known-values.txt ~/mask-demo/masked.sql; then
  echo "Original values found in the masked dump"; false
else
  echo "No original values found in the masked dump"
fi

Ship only masked.dump. Never ship a copy of the masking server's data directory or WAL: the UPDATEs may leave the old row versions on disk there, because vacuum only marks that space reusable rather than wiping it, while pg_dump reads only the current rows.

On staging, restore it as usual:

Bash
createdb shop_staging
pg_restore --no-owner --no-privileges --exit-on-error -d shop_staging ~/mask-demo/masked.dump

Check it worked

Bash
psql -X -d shop_staging -c "
  SELECT c.full_name, c.email, count(o.id) AS orders
  FROM customers c JOIN orders o ON o.customer_id = c.id
  GROUP BY c.id ORDER BY c.id"

Six pseudonymous customers with 10 orders each. The scanner and the known-values check both passed, so the dump you handed over has none of the original emails, phone numbers or names in it.

What you have, and what you do not

You have a pseudonymised copy: much safer than raw production, and still personal data. Treat staging accordingly: limit who can reach it, keep it out of screenshots in public tickets, and delete it on the date in your note. Re-identification stays possible for anyone who holds the key, and sometimes for someone who knows a customer well (one 1968 birth year, one London address, a distinctive order pattern). For data you plan to share outside the team, or keep with no end date, you need real anonymisation methods such as aggregation and statistical checks, and usually advice from whoever handles data protection for you.

Clean up

The raw dump, before.sql and known-values.txt hold real personal data. Remove them as soon as the masked copy is accepted. This removes the practice databases and the whole workspace, including the key, so move the key to your secrets manager first if you want stable pseudonyms next time:

Bash
dropdb shop_staging
dropdb shop_mask
dropdb shop_prod
rm -rf ~/mask-demo

If you created your PostgreSQL role only for this tutorial, remove it too:

Bash
sudo -u postgres dropuser "$(whoami)"

Next steps

  • Use generated data wherever the real thing is not needed: /tutorials/manage-test-data-with-factories-and-builders.
  • Schedule and test the dumps this pipeline starts from: /tutorials/back-up-and-restore-postgresql-with-pg-dump.
  • Set up a fresh PostgreSQL 18 server for the masking machine: /tutorials/install-postgresql-18-on-ubuntu-26-04.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.