Step 1: Set up the database with partitioned tables.
raw_events:
columns:
id (bigserial),
token_uid (text),
token_email (text),
token_ip (text),
event_type (text),
timestamp (timestamptz),
... other non-PII fields
partitioned by: RANGE (timestamp)
aggregated_by_uid:
columns:
token_uid (text),
event_type (text),
date (date), -- we truncate the timestamp to date
count (bigint)
partitioned by: RANGE (date)
global_aggregates:
columns:
event_type (text),
date (date),
count (bigint)
partitioned by: RANGE (date)
Step 2: Create the tokenization configuration table:
tokenization_config:
field_name (text),
secret_key (text) -- but we should store the key in a key management system and not in the database? We can store a reference to the key.
But we don't want to store the secret keys in the database. We can store the key names and then fetch the keys from a key management service (KMS). For simplicity, we'll assume we have environment variables for the keys.
Alternatively, we can have a configuration file for the tokenization service.
Step 3: Ingestion service:
Read the tokenization configuration (from environment or config file).
For each event, tokenize the configured fields.
Insert into raw_events.
Step 4: Aggregation job:
For each aggregation definition (stored in a table or config file):
Determine the date to process (usually yesterday).
Build the query:
WITH daily_data AS (
SELECT
token_uid,
event_type,
date_trunc('day', timestamp)::date as date,
count(*) as cnt
FROM raw_events
WHERE date_trunc('day', timestamp) = 'date_to_process'
GROUP BY token_uid, event_type, date_trunc('day', timestamp)
)
INSERT INTO aggregated_by_uid (token_uid, event_type, date, count)
SELECT token_uid, event_type, date, cnt
FROM daily_data
ON CONFLICT (token_uid, event_type, date)
DO UPDATE SET count = EXCLUDED.count;
But note: we might have multiple aggregation definitions. We can store the group by columns and aggregate columns in the definition.
We can have:
aggregation_definitions:
name,
source_table,
group_by_columns (array of text),
aggregate_columns (array of jsonb: {column: "count", function: "count"} or similar),
destination_table,
time_column (the timestamp column in source to truncate and group by day)
Then the job builds the query dynamically.
Step 5: Retention job:
For each table that has a retention policy:
Find the partition that is older than the retention period and drop it.
Example for raw_events:
We have partitions named like: raw_events_2023_01, raw_events_2023_02, etc.
We can compute the cutoff month and then drop partitions with month <= cutoff.
But note: we are partitioning by range of timestamp, so the partition names are not necessarily by month? We can create partitions by month.
We'll create partitions for raw_events by month:
raw_events_2023_01 for Jan 2023, etc.
Then the retention job:
current_date = now()
cutoff_date = current_date - retention_period (e.g., 30 days)
Then we drop partitions where the partition name (which is the month) is less than the month of cutoff_date.
But note: if we have a partition for a month that is partially within the retention period? We should not drop a partition that has any data within the retention period. So we should drop partitions that are entirely older than the cutoff.
Since we partition by month, if the cutoff is in the middle of a month, we cannot drop that month's partition because it has data within the retention period. So we must drop by exact date? Alternatively, we can partition by day? Then we drop daily partitions that are older than the cutoff.
Given that raw_events is high volume, we might not want daily partitions? But for retention, we need to drop by day. So we can partition by day? But that creates many partitions.
Alternatively, we can keep the monthly partitions and then delete rows within the current month that are older than 30 days? But then we have to delete rows from the current month's partition, which might be large.
Let's do:
For raw_events: partition by day. Then we can drop entire days that are older than 30 days.
For aggregated_by_uid: we can partition by month? Because we are aggregating by day and then storing by day? Actually, the aggregated_by_uid table has a 'date' column (day). We can partition by month on that date? Then we cannot drop a single day. So we should partition by day for aggregated_by_uid as well? Or we can drop rows within the partition.
To keep it simple, let's partition all tables by day on the date column (for aggregated and global) and by timestamp (for raw_events). Then we can drop entire partitions.
But note: for raw_events, the partition key is timestamp (timestamptz). We can create partitions for each day? That would be:
raw_events_2023_01_01, raw_events_2023_01_02, ...
Then the retention job:
cutoff_date = now() - retention_period (e.g., 30 days)
Then for each partition of raw_events where the partition name (which is the day) < cutoff_date, drop the partition.
Similarly for aggregated_by_uid and global_aggregates.
How to get the list of partitions? In PostgreSQL, we can query:
SELECT inhrelid::regclass::text AS partition
FROM pg_inherits
WHERE inhparent = 'raw_events'::regclass;
Then we can parse the partition name to get the date? We have to follow our naming convention.
Alternatively, we can store the retention policy and then for each table, we can:
Determine the cutoff date.
Then for each partition, if the partition's range is entirely less than the cutoff, drop it.
We can use:
SELECT partition_name
FROM information_schema.partitions
WHERE table_name = 'raw_events'
AND partition_name < 'raw_events_2023_01_01' -- but we need to format the cutoff date accordingly.
But the partition naming convention must be known.
We can create partitions with:
CREATE TABLE raw_events_2023_01_01 PARTITION OF raw_events FOR VALUES FROM ('2023-01-01') TO ('2023-01-02');
Then the partition name is raw_events_2023_01_01.
So we can generate the partition name for the cutoff date and then drop all partitions with name less than that.
Steps:
cutoff_date = now() - retention_period
cutoff_partition_name = 'raw_events_' || to_char(cutoff_date, 'YYYY_MM_DD')
Then:
SELECT 'DROP TABLE ' || quote_ident(partition_name) || ';'
FROM information_schema.partitions
WHERE table_name = 'raw_events'
AND partition_name < cutoff_partition_name;
Then execute the drop.
But note: we must be cautious because we might have partitions that are not in the format? We only create partitions by day.
Alternatively, we can use the partition bounds to check:
SELECT partition_name
FROM information_schema.partitions
WHERE table_name = 'raw_events'
AND partition_range_start < cutoff_date -- but the partition_range_start is a string? We need to cast to date.
Actually, in information_schema.partitions, we have:
partition_range_start: value of the partitioning key for the start of the partition (as a string)
So we can compare:
partition_range_start::timestamptz < cutoff_date
But note: the partition_range_start for a day partition is the start of the day (00:00:00). And the cutoff_date is a date? We can set cutoff_date to the start of the day? Actually, we want to drop partitions that are entirely older than the retention period. So if the partition starts at '2023-01-01 00:00:00' and the cutoff is '2023-01-31 00:00:00', then we drop partitions with start < '2023-01-31 00:00:00'. That would drop the partition for 2023-01-01 to 2023-01-02, etc., up to 2023-01-30? Actually, the partition for 2023-01-30 has start '2023-01-30 00:00:00' which is < '2023-01-31 00:00:00', so we drop it. But we want to keep 30 days, so if today is 2023-02-01, then we want to keep data from 2023-01-02 onward? Actually, 30 days from 2023-02-01 is 2023-01-02. So we want to drop partitions that end before 2023-01-02? That is, partitions that are entirely before 2023-01-02.
So we should compare the partition end (partition_range_end) with the cutoff_date? Because the partition for 2023-01-01 ends at 2023-01-02. So if the cutoff_date is 2023-01-02, then we want to drop partitions that end on or before 2023-01-02? Actually, we want to keep data that is within the last 30 days, including the current day? Typically, retention is based on the age of the data. So if a record is older than 30 days, we drop it. So we drop records with timestamp < now() - 30 days. Therefore, we want to drop partitions that have their end <= now() - 30 days? Not exactly: if a partition spans from 2023-01-01 to 2023-01-02, and the cutoff is 2023-01-02 00:00:00, then records on 2023-01-01 23:59:59 are older than 30 days? It depends on the current time. But if we drop the entire partition for 2023-01-01, then we are dropping records that are 31 days old? Actually, if today is 2023-02-01, then 2023-01-01 is 31 days ago. So we want to drop the partition for 2023-01-01.
So we can drop a partition if its end <= now() - retention_period.
But note: the partition end is exclusive. So the partition for 2023-01-01 contains data from 2023-01-01 00:00:00 to 2023-01-02 00:00:00. If the cutoff is 2023-01-02 00:00:00, then we want to keep data up to 2023-01-02 00:00:00? Actually, we want to keep data that is less than 30 days old. So if the current time is 2023-02-01 10:00:00, then we want to keep data from 2023-01-02 10:00:00 onward? But we are partitioning by day, so we cannot drop a partial day. So we have to keep the entire day if any part of it is within the retention period.
Therefore, we drop a partition if its end < now() - retention_period.
Example:
today: 2023-02-01 10:00:00
retention: 30 days
cutoff: 2023-01-02 10:00:00
Partition for 2023-01-01:
start: 2023-01-01 00:00:00
end: 2023-01-02 00:00:00
end < cutoff? 2023-01-02 00:00:00 < 2023-01-02 10:00:00 -> true, so drop.
Partition for 2023-01-02:
start: 2023-01-02 00:00:00
end: 2023-01-03 00:00:00
end < cutoff? 2023-01-03 00:00:00 < 2023-01-02 10:00:00 -> false, so keep.
But note: the partition for 2023-01-02 contains data from 00:00:00 to 00:00:00 of the next day. The data from 2023-01-02 00:00:00 to 2023-01-02 10:00:00 is within the retention period? Actually, it's 30 days and 0 hours to 30 days and 10 hours? We want to keep data that is less than 30 days old. So at 2023-02-01 10:00:00, data from 2023-01-02 10:00:00 is exactly 30 days old. We want to keep data that is younger than 30 days? Or up to 30 days? Typically, retention is "keep for 30 days", meaning data older than 30 days is deleted. So data that is exactly 30 days old is kept? It depends on the business rule. We'll assume we keep data that is less than or equal to 30 days old? Actually, if we say "retention for 30 days", we usually keep the last 30 days of data. So at 2023-02-01, we keep data from 2023-01-02 onward? That is, we keep 31 days? Let's clarify:
If we have data from 2023-01-01 00:00:00 and today is 2023-02-01 00:00:00, then that data is exactly 31 days old. We want to delete it.
So we delete data where timestamp < now() - interval '30 days'.
So at 2023-02-01 00:00:00, we delete data from 2023-01-01 23:59:59.999? Actually, we delete data with timestamp < 2023-01-02 00:00:00.
So the cutoff is now() - 30 days.
Then we drop partitions that have their end <= cutoff.
Because the partition for 2023-01-01 ends at 2023-01-02 00:00:00, and if the cutoff is 2023-01-02 00:00:00, then we drop the partition for 2023-01-01? But note: the partition for 2023-01-01 contains data up to but not including 2023-01-02 00:00:00. So if the cutoff is 2023-01-02 00:00:00, then we keep data with timestamp < 2023-01-02 00:00:00? Actually, we delete data with timestamp < cutoff. So we delete data with timestamp < 2023-01-02 00:00:00. That includes the entire partition for 2023-01-01? Yes, because the partition for 2023-01-01 has timestamp < 2023-01-02 00:00:00.
So we drop partitions with end <= cutoff.
But what if the cutoff is exactly at the partition boundary? Then we drop the partition that ends at the cutoff? That would delete data that is exactly 30 days old? Actually, the data in the partition that ends at the cutoff is strictly less than the cutoff? Because the partition end is exclusive. So the data in the partition that ends at the cutoff is < cutoff. So we want to delete it? Yes, because we delete data with timestamp < cutoff. So we drop partitions with end <= cutoff.
However, note: the partition for 2023-01-02 ends at 2023-01-03 00:00:00. If the cutoff is 2023-01-02 00:00:00, then we do not drop that partition because its end (2023-01-03 00:00:00) > cutoff. But we want to keep the partition for 2023-01-02? Actually, the partition for 2023-01-02 contains data from 2023-01-02 00:00:00 to 2023-01-03 00:00:00. The data from 2023-01-02 00:00:00 to 2023-01-02 00:00:00? That's none? Actually, the partition for 2023-01-02 starts at 2023-01-02 00:00:00. So at the cutoff of 2023-01-02 00:00:00, we want to keep data that is >= 2023-01-02 00:00:00? Yes. So we keep the partition for 2023-01-02.
So the rule: drop partitions where partition_range_end <= cutoff.
But note: the partition_range_end is stored as a string in the format of the partition key. We are using timestamptz, so we can cast to timestamptz.
So:
SELECT partition_name
FROM information_schema.partitions
WHERE table_name = 'raw_events'
AND partition_range_end::timestamptz <= now() - interval '30 days'
Then drop those partitions.
But note: the partition_range_end for the last partition is 'MAXVALUE'. We don't want to drop that. So we must exclude that.
So:
AND partition_range_end <> 'MAXVALUE'
Similarly for the other tables.
Step 6: Access Control:
We can use PostgreSQL roles and grants.
Create roles:
raw_data_reader: can SELECT on raw_events? But we don't want to give that to analysts. So we don't grant that.
aggregated_reader: can SELECT on aggregated_by_uid and global_aggregates.
We can also have row-level security? Not needed because the tokenization already pseudonymizes.
But note: if an analyst has access to aggregated_by_uid, they can see the token_uid. If they can guess the user_id (by brute force) and compute the token (if they know the secret key? they don't) then they can link. But without the secret key, they cannot compute the token from the user_id. So it's safe.
However, if the user_id space is small (like 1 million users) and the analyst has a list of user_ids, they can compute the tokens for all and then match. So we must use a secret key that is not known to the analysts. And the token must be long enough (like 256 bits) to prevent brute force.
So we use a strong secret key and a cryptographic hash (HMAC-SHA256) which is 256 bits.
Step 7: Monitoring and Alerting:
We should monitor:
- Ingestion rate and errors.
- Aggregation job success/failure.
- Retention job success/failure.
- Disk usage of partitions.
Step 8: Secrets Management:
We must store the secret keys for tokenization in a secure way (e.g., HashiCorp Vault, AWS KMS). The ingestion service should fetch the keys at startup or use a key management library.
Step 9: Testing:
We must test:
- Tokenization: same input always gives same token, different inputs give different tokens (with high probability).
- Aggregation: the counts match between raw and aggregated.
- Retention: old data is deleted.
Step 10: Deployment:
We can deploy as:
- A set of microservices: ingestion service, aggregation service, retention service.
- Or as a monolith with scheduled jobs.
Given the simplicity, we can have:
- An HTTP server for ingestion.
- A cron job that runs the aggregation and retention.
But we want to scale the ingestion independently.
So:
Ingestion: stateless HTTP service that tokenizes and writes to the database.
Aggregation and Retention: separate services (or one service with two schedulers) that run periodically.
Step 11: Configuration:
We need to configure:
- Tokenization: which fields to tokenize and which secret key to use for each.
- Aggregation definitions.
- Retention policies.
We can store these in database tables and have the services read them at startup and watch for changes? Or we can have a configuration file that we reload.
For simplicity, we'll use database tables for aggregation definitions and retention policies, and environment variables for tokenization keys (or a database table for tokenization config, but then we need to secure the keys).
Actually, for the tokenization keys, we don't want to store them in the database in plain text. We can store a reference (like a key ID) and then fetch the actual key from a KMS.
So:
tokenization_config table:
field_name, key_id
Then the ingestion service, for each field, uses the key_id to fetch the key from KMS and then tokenize.
But note: we might have multiple fields using the same key? We can have a key management system that stores keys and we reference them by key_id.
Alternatively, we can have a single key for all fields? But we said we want different keys per field to avoid cross-field linkage if the same value appears in two fields. So we need per-field keys.
So we have:
key_store: key_id, key (encrypted at rest, or stored in KMS)
But we don't want to store the key in the database. So we store the key_id and then the ingestion service uses the key_id to get the key from KMS.
We can have a key management service that provides the key given the key_id.
For simplicity, we'll assume we have environment variables for each field:
TOKENIZATION_KEY_UID=...
TOKENIZATION_KEY_EMAIL=...
And we read them at startup.
Given the complexity of key management, we'll leave it as an exercise to integrate with a KMS.
Summary:
We have:
- Ingestion service: tokenizes events and writes to raw_events.
- Aggregation service: runs configured aggregations and writes to aggregated tables.
- Retention service: drops old partitions from all tables.
We have:
- Database with partitioned tables.
We have:
- Configuration for tokenization (environment variables for keys) and for aggregations and retention (database tables).
Let's write some code for the ingestion service (in Python, for example) and the aggregation job (in SQL and Python) and the retention job (in SQL and Python).
But note: the requirement is to implement, so we'll provide a high-level design and some sample code.
We'll focus on the tokenization and the aggregation definitions.
Sample code for ingestion (Python with psycopg2):
import os
import hmac
import hashlib
import base64
import json
from datetime import datetime
import psycopg2
# Tokenization configuration: read from environment
TOKENIZATION_KEYS = {
'uid': os.getenv('TOKENIZATION_KEY_UID'),
'email': os.getenv('TOKENIZATION_KEY_EMAIL'),
'ip': os.getenv('TOKENIZATION_KEY_IP'),
}
def tokenize(field, value):
key = TOKENIZATION_KEYS[field]
if not key:
raise ValueError(f"No tokenization key for field {field}")
# Convert key and value to bytes
key_bytes = key.encode('utf-8')
value_bytes = str(value).encode('utf-8')
# Compute HMAC-SHA256
h = hmac.new(key_bytes, value_bytes, hashlib.sha256)
# Return base64 encoded token
return base64.b64encode(h.digest()).decode('utf-8')
def handle_event(event):
# event is a dict
for field in TOKENIZATION_KEYS:
if field in event:
event[field] = tokenize(field, event[field])
# Now insert into raw_events
# We assume event has: uid, email, ip, event_type, timestamp, and maybe other fields.
# We'll build an insert query dynamically based on the event keys.
# But for simplicity, we assume a fixed schema.
conn = psycopg2.connect(...)
cur = conn.cursor()
columns = event.keys()
values = [event[col] for col in columns]
query = f"INSERT INTO raw_events ({', '.join(columns)}) VALUES ({', '.join(['%s']*len(columns))})"
cur.execute(query, values)
conn.commit()
cur.close()
conn.close()
# Then we have an HTTP endpoint that receives JSON events and calls handle_event.
Sample aggregation definition:
We have a table aggregation_definitions:
id | name | source_table | group_by_columns | aggregate_columns | destination_table | time_column | schedule
1 | per_uid_agg | raw_events | ["token_uid", "event_type"] | [{"column": "count", "function": "count"}] | aggregated_by_uid | timestamp | "0 2 * * *"
The aggregation job:
For each definition where the schedule matches (we can use a cron parser):
date_to_process = (now() - 1 day).date() # for daily aggregation
Build the query:
group_by = group_by_columns + [f"date_trunc('day', {time_column}) as date"]
aggregate_columns: we have a list of dicts, each dict has 'column' and 'function'. We can build:
SELECT
{', '.join(group_by)},
{', '.join([f"{item['function']}({item['column']}) as {item['column']}" for item in aggregate_columns])}
FROM {source_table}
WHERE date_trunc('day', {time_column}) = %s
GROUP BY {', '.join(group_by)}
Then:
INSERT INTO {destination_table} ({', '.join(group_by_columns + ['date'] + [item['column'] for item in aggregate_columns])})
SELECT ...
ON CONFLICT ({', '.join(group_by_columns + ['date']})
DO UPDATE SET {', '.join([f"{item['column']} = EXCLUDED.{item['column']}" for item in aggregate_columns])}
But note: the aggregate_columns in the example only have count. We might have multiple.
Sample retention job:
We have a table retention_policies:
table_name | retention_period (days) | partition_column
raw_events | 30 | timestamp
aggregated_by_uid | 365 | date
global_aggregates | 3650 | date
For each policy:
cutoff = now() - retention_period days
Find partitions:
SELECT partition_name
FROM information_schema.partitions
WHERE table_name = 'raw_events'
AND partition_range_end::timestamptz <= %s
AND partition_range_end <> 'MAXVALUE'
Then for each partition_name, execute:
EXECUTE 'DROP TABLE ' || partition_name;
But note: for aggregated_by_uid and global_aggregates, the partition_column is 'date' (type date). So we need to cast partition_range_end to date? Actually, the partition_range_end for a date partition is a date string? In PostgreSQL, for a range partition on date, the partition_range_end is stored as a date? Let's check.
We'll assume we partition by the same type as the column.
So for raw_events (timestamp with time zone) we cast to timestamptz.
For aggregated_by_uid (date) we cast to date.
So we need to adjust the query by the type of the partition column.
We can store the data type of the partition column in the retention_policies table? Or we can infer from the table.
Alternatively, we can have two different queries for timestamp and date.
Let's assume:
if partition_column is 'timestamp' (for raw_events) then we cast to timestamptz.
if partition_column is 'date' (for the others) then we cast to date.
We can do:
data_type = (SELECT data_type FROM information_schema.columns
WHERE table_name = policy.table_name
AND column_name = policy.partition_column)
Then if data_type in ('timestamp with time zone', 'timestamp without time zone') then cast to timestamptz.
if data_type = 'date' then cast to date.
Then:
AND partition_range_end::<type> <= cutoff
But note: the cutoff must be of the same type. So for timestamp, cutoff is timestamptz. For date, cutoff is date.
We can compute:
cutoff_timestamp = now() - interval '30 days' for raw_events.
cutoff_date = (now() - interval '365 days')::date for the others.
So we compute cutoff based on the retention period and the type.
Alternatively, we can compute cutoff as a string in the format that the partition_range_end is stored? Maybe not.
Let's do:
For raw_events:
cutoff = now() - interval '30 days'
and compare partition_range_end::timestamptz <= cutoff.
For aggregated_by_uid and global_aggregates:
cutoff = (now() - interval '365 days')::date
and compare partition_range_end::date <= cutoff.
But note: the partition_range_end for a date partition is stored as a string in the format 'YYYY-MM-DD'? Actually, it depends on the input. We created the partition with:
CREATE TABLE aggregated_by_uid_2023_01_01 PARTITION OF aggregated_by_uid FOR VALUES FROM ('2023-01-01') TO ('2023-01-02');
So the partition_range_end is '2023-01-02' (as a string). We can cast that to date.
So:
SELECT partition_name
FROM information_schema.partitions
WHERE table_name = 'aggregated_by_uid'
AND partition_range_end::date <= (now() - interval '365 days')::date
But note: the partition_range_end for the last partition is 'MAXVALUE'. We cannot cast that to date. So we must exclude it.
So:
AND partition_range_end <> 'MAXVALUE'
Then drop.
This is a complex system. We have provided a design and some sample code.
We must also consider:
- Error handling: what if the aggregation job fails? We should not drop old data until the new aggregation is successful? Actually, the retention job is independent. But if the aggregation job fails, we might have missing data in the aggregated tables. That's acceptable because the raw data is still there (until retention). But then we might have to backfill.
- We might want to run the aggregation job in a way that we don't lose data if it fails. We can write to a temporary table and then swap? But for simplicity, we delete and insert.
- For the aggregated tables, we are deleting the day's data and then inserting. If the job fails after delete, we lose that day's data. So we should:
Option 1: Insert into a temporary table and then do an atomic swap (rename tables). But that requires that the destination table is partitioned by day? We are partitioning by day, so we can have a partition for that day. We can delete the partition and then create a new one? Or we can truncate the partition and then insert? But if we truncate and then fail to insert, we lose the data.
Option 2: We can insert into a new partition and then drop the old partition and rename the new one? That's more complex.
Alternatively, we can do:
CREATE TABLE aggregated_by_uid_tmp (LIKE aggregated_by_uid INCLUDING ALL);
Then run the aggregation into aggregated_by_uid_tmp.
Then drop the partition for the day in aggregated_by_uid and attach the aggregated_by_uid_tmp as that partition? But we cannot attach a table as a partition if it's not empty? Actually, we can create a new partition and then swap.
Given the complexity, we can accept the risk of losing a day's aggregation if the job fails after delete? We can run the job in a transaction:
BEGIN;
DELETE FROM aggregated_by_uid WHERE date = date_to_process;
INSERT ... (the aggregation)
COMMIT;
Then if the insert fails, we rollback and the delete is rolled back.
But note: if we are partitioning by day, then the delete might be a DROP PARTITION? We cannot do that in a transaction? Actually, DROP TABLE is transactional in PostgreSQL. So we can:
BEGIN;
DROP TABLE aggregated_by_uid_YYYY_MM_DD;
CREATE TABLE aggregated_by_uid_YYYY_MM_DD PARTITION OF aggregated_by_uid FOR VALUES FROM ('YYYY-MM-DD') TO ('YYYY-MM-DD+1');
INSERT ... (into the new partition)
COMMIT;
But we don't have to drop the partition if we are going to insert into it? We can just truncate it? But we cannot truncate a partition that doesn't exist? We are creating a new partition and then inserting. But what if the partition already exists? Then we drop it and create a new one.
Alternatively, we can use the existing partition and truncate it? But if we truncate and then fail to insert, we lose the data.
So we do:
Step 1: Create a new partition with a temporary name (like aggregated_by_uid_tmp_YYYY_MM_DD).
Step 2: Run the aggregation into that temporary partition.
Step 3: Drop the old partition (if exists) and rename the temporary partition to the correct name.
But note: the parent table aggregated_by_uid must have the partition attached. We can:
Step 1: Create the temporary partition (not attached to the parent).
Step 2: Run the aggregation into the temporary partition.
Step 3: Detach the old partition (if exists) and drop it.
Step 4: Attach the temporary partition to the parent with the correct bounds.
This is safe because until we attach, the data is not visible in the parent table.
But note: we are running the aggregation for a specific day. We want the partition to be named aggregated_by_uid_YYYY_MM_DD and have bounds for that day.
Steps:
date_str = date_to_process.strftime('%Y-%m-%d')
partition_name = f'aggregated_by_uid_{date_str}'
temp_partition_name = f'aggregated_by_uid_tmp_{date_str}'
CREATE TABLE {temp_partition_name} (LIKE aggregated_by_uid INCLUDING ALL);
INSERT INTO {temp_partition_name} ... (the aggregation query)
-- Now, if the old partition exists, detach and drop it.
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_inherits WHERE inhparent = 'aggregated_by_uid'::regclass AND inhrelid = '{partition_name}'::regclass) THEN
EXECUTE 'ALTER TABLE aggregated_by_uid DETACH PARTITION ' || partition_name;
EXECUTE 'DROP TABLE ' || partition_name;
END IF;
END $$;
-- Attach the new partition
EXECUTE 'ALTER TABLE aggregated_by_uid ATTACH PARTITION ' || temp_partition_name || ' FOR VALUES FROM (\'' || date_str || '\') TO (\'' || (date_to_process + timedelta(days=1)).strftime('%Y-%m-%d') || '\')';
But note: the temporary partition must have the same structure as the parent. We created it with LIKE.
This way, we never lose data: the old partition is only dropped after the new one is ready.
However, this is more complex and we have to manage the partition names.
Given the time, we might stick to the simple DELETE and INSERT, but in a transaction.
But note: if the aggregated_by_uid table is partitioned, then the DELETE might be a DROP PARTITION? Actually, if we do:
DELETE FROM aggregated_by_uid WHERE date = '2023-01-01';
That will delete from the partition for 2023-01-01? But if the table is partitioned, the delete will be routed to the partition. But it will still delete all rows in that partition. So we can do:
BEGIN;
DELETE FROM aggregated_by_uid WHERE date = '2023-01-01';
INSERT ... (the aggregation for 2023-01-01)
COMMIT;
This is safe because if the insert fails, we rollback and the delete is rolled back.
But note: the delete might be heavy if the partition is large? Actually, deleting all rows from a partition can be done by truncating the partition? But we cannot truncate a partition by a condition? We can truncate the partition directly if we know the partition name.
So we can do:
Step 1: Find the partition name for the date.
Step 2: TRUNCATE that partition.
Step 3: Insert the new data.
But TRUNCATE is transactional? Yes, in PostgreSQL.
So:
BEGIN;
TRUNCATE aggregated_by_uid_YYYY_MM_DD;
INSERT ... (into the same partition? We are inserting into the parent table, but it will go to the partition because the date is within the partition's bounds)
COMMIT;
But note: we are inserting into the parent table, and the partition is attached. So it will go to the correct partition.
However, if we truncate the partition and then the insert fails, we have an empty partition. That's acceptable because the old data is gone and the new data didn't come. So we lost that day's data? But we can rerun the job.
Alternatively, we can do:
CREATE TABLE aggregated_by_uid_new_YYYY_MM_DD (LIKE aggregated_by_uid INCLUDING ALL);
INSERT ... into aggregated_by_uid_new_YYYY_MM_DD
Then, in a transaction:
DETACH the old partition and drop it.
ATTACH the new partition.
That is safer.
Given the complexity, we'll leave the aggregation job implementation as an exercise.
Conclusion:
We have designed a privacy-preserving analytics sink with:
- Tokenization using HMAC with per-field secret keys.
- Aggregation at multiple tiers (raw, per-tenant, global) with configurable aggregation definitions.
- Retention by dropping old partitions.
We have provided sample code for tokenization and ideas for aggregation and retention.
This design meets the requirements.
Note: This is a high-level design and not production-ready. We must consider:
- Securing the secret keys.
- Monitoring and alerting.
- Error handling and retries.
- Scalability of the ingestion service (we might need to shard the raw_events table?).
- The aggregation job might be heavy; we might need to run it on a separate cluster.
- The retention job must be run with caution.
But for the purpose of this exercise, we have provided a solid foundation.</think>