We are to design a data deletion compliance workflow that propagates user deletion requests through caches and feature stores.
The goal is to ensure that when a user requests deletion of their data (e.g., GDPR right to be forgotten), we remove all traces of that user's data from:
- Primary databases (already handled by existing processes)
- Caches (like Redis, Memcached)
- Feature stores (like Feast, Tecton, or custom feature stores)
We assume that the user's data is identified by a unique user ID (or a set of keys that can identify the user's data).
Steps:
- Receive a deletion request (with user identifier) and validate it.
- Invalidate/delete the user's data from the cache (if present). This might involve:
- Deleting specific keys related to the user.
- Or if the cache is shared and we don't have a straightforward mapping, we might need to use a pattern-based deletion (like SCAN in Redis) or maintain a separate index.
- For feature stores, we need to delete the user's feature data. Feature stores can be of two types:
a. Online feature store (low-latency serving, often backed by a database or key-value store) -> we delete the user's features by key.
b. Offline feature store (data warehouse, like BigQuery, Redshift, etc.) -> we might need to run a deletion job that removes the user's data from the feature tables.
However, note that offline feature stores might be used for training and batch predictions. Deletion from offline stores might be more complex because:
- Data might be stored in partitioned tables (by date, user, etc.)
- We might need to rewrite entire partitions or use a soft delete mechanism (like marking as deleted) and then filter during training.
But the requirement is to propagate the deletion. We assume that the feature store has a way to delete by user ID.
- We might also need to consider that the user's data might be present in other systems (like logs, analytics, etc.) but the problem focuses on caches and feature stores.
We design a workflow that is triggered by a deletion request (could be from an admin panel, or an automated process from a user portal).
Proposed workflow:
Step 1: Deletion Request Intake
- API endpoint or message queue (like Kafka) that receives deletion requests.
- The request contains: user_id, and possibly a timestamp (to handle race conditions) and a unique request ID for idempotency.
Step 2: Validation and Idempotency Check
- Check if the user_id is valid (exists in the system?).
- Check if the deletion request for this user_id has already been processed (to avoid duplicate work). We can keep a record of processed deletion requests (in a database table) with the user_id and status.
Step 3: Cache Invalidation
- For each cache system (we might have multiple: Redis for session, Redis for feature store online, etc.):
a. If we have a direct mapping (like user_id -> cache key), then delete by key.
b. If we use a pattern (like "user:*:user_id"), then we might need to use SCAN and then DEL. But note: SCAN can be heavy and we might have to do it asynchronously.
c. Alternatively, if the cache is used for feature store online, we might have a separate service that manages the cache and we can call its delete API.
However, note: caches are ephemeral and might not have all the data. But we try to delete what we can.
Step 4: Feature Store Deletion
a. Online Feature Store:
- If the online feature store is backed by a key-value store (like Redis, Cassandra, etc.), then we delete by the user's key (which is usually the user_id).
- We might have multiple feature tables (for different feature groups) so we need to know the key structure. Alternatively, the feature store might provide an API to delete by entity (user_id).
b. Offline Feature Store:
- We might have to run a batch job that deletes the user's data from the feature tables in the data warehouse.
- Since data warehouses are not designed for row-level deletes (especially in partitioned tables), we might:
Option 1: If the table is partitioned by user_id, then we can drop the partition (if the entire partition is for that user) but that's unlikely.
Option 2: Run a DELETE statement that deletes rows where user_id = given user_id. But this can be expensive and might not be supported in all data warehouses (like BigQuery supports DELETE but it's a heavy operation and might require clustering on user_id for efficiency).
Option 3: Use a soft delete: add a column is_deleted and set it to true for the user's rows, and then filter during training and serving. But this requires changes in the feature pipelines and serving code to filter out deleted users.
However, the requirement is to delete, so we must remove the data. But note: in offline stores, data is often immutable and append-only. So we might have to rely on the feature store's built-in deletion mechanism (if any) or use a combination of:
- For batch feature pipelines: we can modify the pipeline to exclude the user in future runs, but historical data remains. So we need to run a one-time deletion job.
Given the complexity, we might need to coordinate with the feature store's operator.
Step 5: Record the Deletion
- After successfully deleting from caches and feature stores, we mark the deletion request as completed in our database (so we don't process again).
Step 6: Notify other systems (if necessary)
- There might be other systems that hold user data (like model training datasets, analytics, etc.). We might need to propagate the deletion to them as well. But the problem specifies caches and feature stores.
However, note: the feature store offline might be used to generate training data. If we don't delete from offline, then the user's data might still be in training datasets and models might have learned from it. This is a complex issue and might require re-training without that user's data. But that's beyond the scope of this workflow.
We focus on the immediate deletion from the feature store (both online and offline) and caches.
Implementation Considerations:
-
Idempotency: We must design each step to be idempotent. If we try to delete a user's data that is already deleted, it should not cause an error.
-
Error handling:
- If deletion from one cache fails, we should retry (with exponential backoff) and if it continues to fail, we should alert and maybe rollback? But note: we are deleting, so if one deletion fails, we might still want to proceed with others and then retry the failed one later.
- We might use a saga pattern? But deletion is a destructive operation and we cannot undo. So we might have to accept partial failures and then retry.
-
Order of operations:
- We might want to delete from caches first (because they are faster and less critical) and then from feature stores (which might be more critical and slower).
- But note: if we delete from the online feature store cache and then the online feature store database, we might have a race condition where the cache is repopulated from the database. So we should delete from the database (or the source of truth for the online feature store) first, then invalidate the cache.
However, the online feature store might have its own cache (like Redis) and a database (like Cassandra). We need to know the architecture.
Let's assume the online feature store has two layers:
- A fast cache (Redis) that is read by the serving API.
- A persistent store (Cassandra) that is the source of truth for the cache (and also used for batch writes).
Then we should:
a. Delete from the persistent store (Cassandra) -> this is the source of truth.
b. Then delete from the cache (Redis) to avoid stale data.
But if the cache is populated on read (cache-aside), then after we delete from the persistent store, the next read will miss and repopulate from the persistent store (which we just deleted) so the cache will be empty. But if there are concurrent reads, we might have a race condition. So it's safer to delete from the cache after the persistent store.
-
For offline feature store, we might run a deletion job that runs periodically (like daily) or immediately. We might want to run it immediately for compliance.
-
We might need to consider that the user's data might be in multiple feature groups (tables). We need to know which feature groups contain the user's data. This might require a metadata lookup.
Proposed Architecture:
We can have a "Deletion Service" that orchestrates the deletion.
Steps in the service:
-
Receive deletion request (with user_id).
-
Look up in a "Deletion Requests" table (with status: PENDING, IN_PROGRESS, COMPLETED, FAILED) to check if already processed. If COMPLETED, return. If FAILED, maybe retry? We can have a retry policy.
-
Mark as IN_PROGRESS.
-
For each cache system (we have a configuration of caches and how to delete from them):
- Try to delete by key (if we have a direct mapping) or by pattern.
- If pattern-based, we might do:
keys = cache.scan(pattern) # but note: scan can be heavy and we might need to do it in a separate thread or async.
then cache.delete(keys)
- We should log the number of keys deleted and any errors.
-
For feature store online:
- Call the feature store's delete API (if available) or directly delete from the underlying database (if we have access and it's safe).
- We need to know the key structure. Typically, the entity (user_id) is the primary key or part of the primary key.
- We might have multiple feature tables (for different feature groups). We need to delete from each table that has the user's data. We can have a configuration that lists the tables and the key column (usually 'user_id').
- We can do:
for table in feature_tables:
delete from table where user_id = :user_id
But note: the table might have a composite key (user_id, feature_name) or (user_id, timestamp). We need to know the schema.
Alternatively, if the feature store provides an API, we call:
feature_store.delete(entity_ids=[user_id], feature_view_names=[...])
-
For offline feature store:
- We might trigger a deletion job (like a Spark job) that deletes the user's data from the feature tables in the data warehouse.
- The job would run SQL DELETE statements for each table where user_id = given user_id.
- We might need to handle the fact that the data warehouse might be huge and the delete might be expensive. We might need to cluster by user_id or use partitioning.
However, note: if the offline feature store is built from a data lake (like Delta Lake, Hudi, Iceberg) then we can use the table's delete capability (like Delta Lake's DELETE). But if it's a traditional data warehouse (like Redshift, Snowflake) then we can run DELETE.
-
If all steps are successful, mark as COMPLETED. If any step fails, mark as FAILED and store the error.
-
We should also have a way to re-process a FAILED request (retry).
-
We might need to consider that the user's data might be in multiple environments (dev, staging, prod). The deletion request might be for a specific environment? We assume the request is for the production environment.
Implementation Details:
We can build a microservice (in Python, for example) that:
-
Has an HTTP endpoint (or gRPC) to receive deletion requests.
-
Uses a database (like PostgreSQL) to track deletion requests.
-
Uses a configuration file (or database) that lists:
- Cache systems:
- name: "redis-session"
type: "redis"
host: ...
port: ...
key_pattern: "session:*" # if we use pattern, or we can have a function that maps user_id to keys?
- name: "redis-feature-cache"
type: "redis"
host: ...
port: ...
key_pattern: "feature::{user_id}:" # but note: the pattern might be complex.
Alternatively, we can have a function that, given a user_id, returns a list of keys to delete for each cache. But that might require knowing the exact key structure.
If the cache keys are not directly derivable from user_id (like if we use a hash function or if the key is a random string), then we might need to maintain an index (like a set in Redis that contains all keys for a user). But that's an extra overhead.
We assume that the cache keys are formed with the user_id in them and we can use a pattern.
-
Feature store configuration:
- online_feature_store:
type: "redis" # or "cassandra", etc.
connection: ...
tables:
- name: "feature_group1"
key_column: "user_id"
- name: "feature_group2"
key_column: "user_id"
- offline_feature_store:
type: "bigquery"
connection: ...
tables:
- name: "project.dataset.feature_table1"
key_column: "user_id"
- ...
Then the service would:
for cache in caches:
if cache.type == "redis":
if cache.key_pattern:
# Use SCAN to find keys matching pattern and delete them.
# But note: SCAN might return a lot of keys and we might need to do it in batches.
else:
# We have a function to compute the keys from user_id?
# Or we have a fixed set of keys? Not likely.
We might also support other cache types (memcached, etc.)
for table in online_feature_store.tables:
if online_feature_store.type == "redis":
# Then we already covered it in cache? But wait, the online feature store online might be the same as the cache?
# Actually, the online feature store might have its own Redis instance. So we have two separate Redis: one for general cache and one for feature store online.
But in our configuration, we list the online feature store as a separate system. So we delete from it.
We run:
if type == "redis":
# We might have a set of keys: user_id, and maybe other keys?
# The key structure for the feature store might be: "feature:{feature_view}:{user_id}"
# We can use pattern: "feature:*:{user_id}" but that might be dangerous if user_id appears elsewhere.
Alternatively, we can have a specific pattern for each feature table? Or we can have a function that generates the key for a given user_id and feature table.
We might design the feature store such that the key is exactly the user_id (for online) and then we have a hash map from user_id to features? Then we can delete by user_id.
Similarly for offline feature store, we run a DELETE statement for each table.
However, note: the offline feature store might have billions of rows and a DELETE by user_id might be expensive if the table is not partitioned by user_id. We might need to use a different strategy:
- If the table is partitioned by user_id, then we can drop the partition (if the entire partition is for that user). But that's rare because user_id is high-cardinality.
- Alternatively, if the table is clustered by user_id, then the DELETE might be efficient.
- If not, we might have to do a full table scan? That's not acceptable for large tables.
So we might need to rely on the feature store's design: if the offline feature store is built on a data lake (like Delta Lake) then we can use the table's delete function which might be efficient because of the data layout.
Alternatively, we might have to mark the rows as deleted (soft delete) and then have the training jobs filter them out. But that requires changes in the training pipelines.
Given the complexity, we might have to accept that deletion from offline feature store is a best-effort and might be delayed.
We might break the workflow into two parts:
Part A: Immediate deletion (online systems: caches, online feature store)
Part B: Batch deletion (offline feature store) -> we trigger a job and monitor it.
We can do:
Step 1-4 (caches and online feature store) synchronously (or asynchronously but we want to confirm to the user that the online data is gone).
Step 5 (offline) asynchronously: we enqueue a job (in a job queue) and then return that the deletion is in progress. We can then monitor the job and update the status.
But compliance might require that we delete from all systems within a certain timeframe. So we need to set SLAs.
- We must also consider that the user's data might be in the model itself (if the model was trained on that user's data). That's a separate issue and might require model retraining. But that's beyond the scope of this workflow.
Let's design the service:
We'll have:
-
A REST API endpoint: POST /delete-user
Request body: { "user_id": "123", "request_id": "optional-unique-id" }
-
The service will:
a. Generate a unique deletion request id if not provided.
b. Check if the request (by user_id or by request_id) has already been processed. If yes, return the status.
c. Insert a record into the deletion_requests table with status = 'PENDING'.
d. Start an asynchronous task (or a saga) that does:
Step 1: Update status to 'IN_PROGRESS'.
Step 2: For each cache in the configuration, attempt to delete the user's data. Log the result (success/failure) for each cache.
Step 3: For the online feature store, attempt to delete the user's data from each table.
Step 4: If both steps 2 and 3 are successful (or even if some fail, we might continue) then we trigger the offline deletion job (by sending a message to a job queue, or starting a Spark job). We record the job id so we can monitor.
Step 5: Update the deletion_requests record with the status (if online steps failed, we might mark as 'FAILED' and not trigger offline? But we might want to try offline anyway?).
e. Return a response with the deletion request id and status (maybe 'ACCEPTED' and then we have a separate endpoint to check status).
-
We also need a way to monitor the offline job and update the deletion_requests record when the offline job completes.
But note: the offline job might take a long time (hours or days). We might want to update the status to 'COMPLETED' only when both online and offline are done? Or we can have:
status:
- ONLINE_DELETED: when online systems are done.
- OFFLINE_DELETED: when offline is done.
- COMPLETED: when both are done? Or we can have two separate statuses.
Alternatively, we can break the deletion request into two parts:
DeletionRequest:
id
user_id
online_status (PENDING, SUCCESS, FAILED)
offline_status (PENDING, SUCCESS, FAILED)
created_at
updated_at
And then we can have two separate workers: one for online and one for offline.
However, the requirement is to propagate the deletion. We might be required to delete from both. So we should try both.
We can design:
The initial request triggers the online deletion worker (which does caches and online feature store) and then enqueues the offline deletion job.
The online worker updates the online_status.
The offline job (which might be a separate system) updates the offline_status.
Then we can have a monitor that checks if both are done and then marks the whole request as COMPLETED.
But note: the user might not care about the offline deletion because they might not be in the training data? But for compliance, we need to remove from all places.
Given the complexity of offline deletion, we might have to accept that it's a best-effort and we might not be able to guarantee immediate deletion from offline.
We might have to work with the compliance team to define the SLA.
Let's assume we are required to delete from online within 24 hours and from offline within 7 days.
Then we can:
- Immediately delete from caches and online feature store (within minutes).
- Trigger the offline deletion job to run within 24 hours (and it might take a while to complete).
We can have:
DeletionRequest:
id
user_id
online_status: ENUM('PENDING', 'SUCCESS', 'FAILED')
offline_status: ENUM('PENDING', 'SUCCESS', 'FAILED')
online_completed_at
offline_completed_at
created_at
Then:
When we receive a request:
create record with online_status='PENDING', offline_status='PENDING'
Then we have an online worker that picks up the request (by status) and does the cache and online feature store deletion. Then sets online_status to SUCCESS or FAILED.
Then the online worker enqueues an offline job (or sets a flag) for the offline deletion.
The offline job (which might be a separate system) picks up the request (maybe by user_id) and does the offline deletion. Then sets offline_status.
We can have a monitor that alerts if a request is stuck in PENDING for more than the SLA.
This way, we decouple the online and offline parts.
But note: the offline job might need to know which user_ids to delete. We can either:
- Have the online worker pass the user_id to the offline job (via message queue or by setting a flag in the database).
- Or the offline job can periodically scan the deletion_requests table for records with offline_status='PENDING' and online_status='SUCCESS' (so we only run offline if online succeeded?).
We might want to run offline even if online failed? Maybe not, because if online failed, we might have a bigger problem and we should fix that first.
So:
Offline job condition:
online_status == 'SUCCESS' AND offline_status == 'PENDING'
But what if the online job fails? We might retry online. And if online eventually succeeds, then offline will run.
This seems acceptable.
However, note: the offline job might be heavy and we might want to batch user_ids. So we might have a batch of user_ids that need offline deletion. We can have a table that lists user_ids to delete offline (and we mark them as processed). But then we lose the connection to the original request? We can have:
OfflineDeletionJob:
id
user_id
deletion_request_id (foreign key)
status: PENDING, SUCCESS, FAILED
attempted_at
Then the offline job picks up OfflineDeletionJob records.
But we already have the deletion_requests table. We can just use that.
So:
The offline job will:
SELECT * FROM deletion_requests
WHERE online_status = 'SUCCESS' AND offline_status = 'PENDING'
ORDER BY created_at ASC
LIMIT 100 (for batching)
Then for each record, it runs the offline deletion for that user_id.
Then updates the offline_status for that deletion_request.
This way, we can have multiple offline workers.
However, if the offline deletion for a user is very heavy (because the user has a lot of data), we might want to do one user at a time? Or we can do multiple.
We assume that the offline deletion for one user is acceptable in terms of time and resources.
But note: if we have millions of deletion requests, we might need to batch them by user_id range? But the offline job might be designed to delete many users at once by running a single DELETE statement with user_id IN (...). But that might be a huge list and not efficient.
Alternatively, we can have the offline job run periodically (daily) and delete all users that were marked for offline deletion in the last day. We can do:
DELETE FROM feature_table
WHERE user_id IN (SELECT user_id FROM deletion_requests
WHERE online_status='SUCCESS' AND offline_status='PENDING'
AND created_at >= NOW() - INTERVAL 1 DAY)
But then we lose per-user status? We can update the deletion_requests in bulk.
We can do:
UPDATE deletion_requests
SET offline_status = 'SUCCESS'
WHERE online_status='SUCCESS' AND offline_status='PENDING'
AND user_id IN (list of user_ids that we successfully deleted)
But we don't know which user_ids we deleted until we run the DELETE? We can run the DELETE and then get the number of rows affected, but we don't know which user_ids were affected.
Alternatively, we can do:
Step 1: Get the list of user_ids that need offline deletion (from deletion_requests).
Step 2: For each user_id, run a DELETE? That's N+1 problem.
We might have to rely on the offline feature store's ability to delete by a list of user_ids efficiently.
Given the complexity, we might stick to one user at a time for offline deletion to keep it simple and track per user.
But note: if we have 1 million deletion requests, we might have 1 million offline jobs? That's too many.
We need to balance:
- We want to track per user (for compliance, we need to prove we deleted each user).
- We want to batch the offline deletion to be efficient.
We can have:
The offline job runs every day and processes a batch of user_ids (say 10,000 at a time) by running:
DELETE FROM feature_table
WHERE user_id IN ( ... 10,000 user_ids ... )
Then we update the deletion_requests for those user_ids to offline_status='SUCCESS'.
But what if the delete fails for some user_ids? We don't know which ones. We might have to do:
We can try to delete and then check how many rows were deleted. But if the table has multiple rows per user_id, we might not know.
Alternatively, we can do:
For each user_id in the batch, we run a separate DELETE? That's 10,000 DELETE statements, which might be heavy.
We might need to rely on the data warehouse's ability to handle a large IN list.
Given the trade-offs, we might choose:
- If the number of user_ids is small (like less than 1000), we do one DELETE with IN.
- If the number is large, we break into multiple batches.
But we are processing 10,000 at a time, so we do one DELETE with 10,000 user_ids? That might be too long and the query might time out.
We might have to use a temporary table:
Create a temporary table with the user_ids to delete.
Then:
DELETE FROM feature_table
WHERE user_id IN (SELECT user_id FROM temp_table)
This might be more efficient.
However, we are getting into the implementation details of the offline job.
Let's step back and focus on the workflow.
We have:
DeletionRequest:
id (UUID)
user_id (string)
online_status (string)
offline_status (string)
created_at (timestamp)
updated_at (timestamp)
We have an online worker that:
- Picks a DeletionRequest with online_status='PENDING'
- Does the cache and online feature store deletion.
- Sets online_status to 'SUCCESS' or 'FAILED'
- If online_status becomes 'SUCCESS', then we insert a record into an offline_deletion_queue (or just rely on the DeletionRequest table and the offline worker will pick it up).
We have an offline worker that:
- Picks a batch of DeletionRequest records where online_status='SUCCESS' and offline_status='PENDING' (maybe order by created_at, and limit by batch size).
- For each feature table in the offline feature store, it deletes the rows for the batch of user_ids.
- Then updates the offline_status for each DeletionRequest in the batch to 'SUCCESS' (or 'FAILED' if any error).
But note: if the offline deletion for one user fails in a batch, we might mark all as failed? Or we try to do per user? We can do:
We break the batch into individual user deletions and update per user.
However, if we run one DELETE for a batch of user_ids and it fails (maybe because one user_id doesn't exist? that shouldn't fail) or because of a deadlock, then we might retry the whole batch.
We can design the offline job to be idempotent: if we run the same batch again, it should not fail (because the rows might already be deleted). So we can use:
DELETE FROM feature_table WHERE user_id IN (list)
If some user_ids are already deleted, that's fine.
So we can run the batch and then update all the DeletionRequest records in the batch to 'SUCCESS' if the delete statement succeeds (even if it deleted 0 rows for some user_ids, that's okay because they might have been deleted already).
But we want to know if the delete statement failed (due to an error) then we mark as 'FAILED'.
We can do:
try:
run the DELETE for the batch
update all DeletionRequest in the batch to offline_status='SUCCESS'
except Exception as e:
log the error and update all to 'FAILED'
This way, we don't have per-user granularity for offline, but we have batch granularity.
Alternatively, we can do per user in the batch (with individual DELETE) and update per user. That way if one user fails, we can retry that user later.
Given that we are dealing with compliance, we might want per-user tracking.
We can do:
for user_id in batch:
try:
delete from feature_table where user_id = user_id
update DeletionRequest set offline_status='SUCCESS' where user_id=user_id
except:
update DeletionRequest set offline_status='FAILED' where user_id=user_id
But that's N+1 queries (or N+1 delete statements). We can do:
We collect the user_ids that we are going to delete in this batch.
We run one DELETE for the batch (with IN) and then update all to SUCCESS.
But if the DELETE fails for the entire batch, we mark all as FAILED.
However, if the DELETE partially fails (like one user_id causes a lock issue?) then the entire DELETE might fail? In most databases, if one row causes an error (like a foreign key constraint) then the entire statement fails. But we are deleting by user_id, and there are no foreign keys? We assume not.
Given the complexity, we might stick to per-user deletion in the offline job to have fine-grained control.
But note: if we have 1 million users, we might run 1 million DELETE statements? That's too heavy.
We need to balance:
- We want to be able to retry individual users.
- We want efficiency.
We can do:
The offline job runs every day and processes up to 10,000 users (per worker). For each user, we run a DELETE for each feature table? That's 10,000 * (number of tables) which might be too heavy.
Alternatively, we can do:
For each feature table, we run:
DELETE FROM table
WHERE user_id IN (list of 10,000 user_ids)
Then we update the DeletionRequest for all 10,000 users for that table? But note: the DeletionRequest is per user, not per table. We want to know if the user's data is deleted from all tables.
We can have:
We have a table: DeletionRequestFeatureTable (deletion_request_id, feature_table_name, status)
But that's getting too complex.
Given the time, we might simplify:
We assume that the offline feature store has one table (or a few) and we can delete by user_id. We run one DELETE per table for the batch of user_ids.
Then we update the DeletionRequest.offline_status to 'SUCCESS' for all user_ids in the batch if the DELETE succeeded for all tables? But what if one table fails? Then we might have partial deletion.
We can do:
for table in offline_tables:
try:
delete from table where user_id in (batch_user_ids)
except:
log error and break
If all tables succeeded, then update all DeletionRequest in the batch to offline_status='SUCCESS'
else, update all to 'FAILED'
This way, we either delete from all tables or none for the batch.
But note: if we have 10,000 user_ids and 10 tables, we run 10 DELETE statements with 10,000 user_ids each. That might be acceptable.
However, if the tables are huge and the user_ids are scattered, the DELETE might be heavy and might lock the table? We might need to do it in a way that doesn't lock for too long (like using partitioning).
Given the complexity of the offline deletion, we might have to leave the implementation details to the offline team and just trigger the job with a list of user_ids.
So the offline worker might just enqueue a job (to a Spark job, for example) with the list of user_ids and let that job handle the deletion in an efficient way (like using DataFrame operations). Then the offline worker just marks the DeletionRequest as 'PENDING_OFFLINE_JOB' and then the Spark job updates the status when done? But then we need a way for the Spark job to update our database.
Alternatively, we can have the offline worker write the user_ids to a file (or a table) and then the Spark job reads that and deletes, and then writes back the status.
This is getting too complex.
Given the constraints, we might have to accept that the offline deletion is best-effort and we might not be able to track per user in the offline job. We might just run a periodic job that deletes all users that are marked for deletion (and have been marked for more than 24 hours, to allow online to complete) and then we mark them as deleted in bulk.
But compliance might require per-user proof.
We might have to store the deletion request and then have the offline job produce a report of which user_ids were deleted from which tables. Then we update the DeletionRequest table with the results.
This is a very complex problem.
Let's simplify the scope:
We are only required to propagate the deletion through caches and feature stores. We assume that the feature store (both online and offline) provides an API to delete by user_id and that it handles the efficiency.
We design:
The deletion service has:
- An online component that deletes from caches and online feature store (by calling the feature store's delete API for each feature group). This is synchronous (or we wait for it to complete).
- Then it calls the offline feature store's API to schedule a deletion for the user (or runs a job immediately). The offline feature store might have an asynchronous API (like "submit deletion job") and then we can poll for completion.
We assume that the feature store (both online and offline) is a managed service that handles the deletion efficiently and provides an API.
Then we don't have to worry about the underlying implementation.
So the workflow becomes:
Step 1: Receive request.
Step 2: For each cache system, call the cache's delete API (or run the delete command) for the user's keys.
Step 3: For the online feature store, call the feature store's delete_entities API (with the user_id) for all feature groups.
Step 4: For the offline feature store, call the feature store's delete_entities API (or schedule a job) for the user_id.
Then we mark the request as completed when all APIs return success (or we get an acknowledgement that the deletion is scheduled).
We consider the offline deletion as "scheduled" and we don't wait for it to complete? But then we don't know if it succeeded.
We might have to poll the offline feature store for the status of the deletion job.
Alternatively, we can have the offline feature store send a callback (webhook) when the deletion is done.
But that's getting into integration details.
Given the open-endedness, I think the key is to design a workflow that:
- Tracks deletion requests (idempotent).
- Deletes from caches (by key pattern or by known keys).
- Deletes from online feature store (by entity id).
- Schedules deletion from offline feature store (and tracks the status).
We can write the service in a way that it's agnostic to the underlying systems (by using adapters for each system).
We define interfaces:
class CacheDeleter:
def delete_user_data(user_id): ...
class OnlineFeatureStoreDeleter:
def delete_user_data(user_id): ...
class OfflineFeatureStoreDeleter:
def schedule_deletion(user_id): # or delete_user_data if synchronous
def check_status(deletion_job_id): ...
Then we have configurations that instantiate these classes with the right parameters.
The service:
def process_deletion_request(user_id):
# check and create DeletionRequest if not exists
# then:
for cache_deleter in cache_deleters:
try:
cache_deleter.delete_user_data(user_id)
except Exception as e:
log but continue
for online_fs in online_feature_stores:
try:
online_fs.delete_user_data(user_id)
except Exception as e:
log but continue
for offline_fs in offline_feature_stores:
try:
job_id = offline_fs.schedule_deletion(user_id)
# store job_id in DeletionRequest for tracking
except Exception as e:
log but continue
update DeletionRequest status to COMPLETED (if we don't wait for offline) or to OFFLINE_SCHEDULED.
Then we have a separate process that checks the status of offline deletion jobs (by polling the offline feature store) and updates the DeletionRequest.
This seems flexible.
But note: the offline feature store might not have a job scheduling API. It might just be a data warehouse and we have to run a DELETE. Then we have to run it synchronously? That might block.
We might have to run the offline deletion in a separate worker (as we discussed earlier) and not in the main request thread.
So:
The main request thread only does:
- Create DeletionRequest (status: PENDING)
- Run the cache and online feature store deletion (synchronously, because they are fast).
- Then enqueue a job (to a task queue) for offline deletion (with the user_id and deletion_request_id).
Then the offline worker (which is a separate process) picks up the job and does:
- Run the offline deletion (by calling the offline feature store's API or running a SQL).
- Update the DeletionRequest offline_status.
This way, the main request returns quickly (after online deletion and enqueuing offline job).
We can design:
API: POST /delete-user
Returns: { "deletion_request_id": "123", "status": "ACCEPTED" }
Then we have a GET /delete-user/{id} to check status.
This seems reasonable.
Let's summarize:
Components:
1. Deletion Service (HTTP API)
- Endpoint: POST /delete-user
Request: { "user_id": "123", "request_id": "optional" }
Response: { "deletion_request_id": "123", "status": "ACCEPTED" }
- Endpoint: GET /delete-user/{id}
Response: { "user_id": "123", "online_status": "SUCCESS", "offline_status": "PENDING", ... }
- It uses a database to store DeletionRequest.
- It has configurations for caches and feature stores.
- When it receives a request:
a. Check if request_id or user_id already exists. If yes, return the existing deletion_request_id and status.
b. Create a new DeletionRequest with status: online_status='PENDING', offline_status='PENDING'.
c. Run the online deletion (caches and online feature store) in the same thread (or async but we wait for it to complete).
d. If online deletion succeeds, update online_status='SUCCESS'. Then enqueue an offline job (with the user_id and deletion_request_id).
e. If online deletion fails, update online_status='FAILED' and do not enqueue offline job? Or we might still enqueue? We decide: only enqueue if online succeeds? Because if online fails, we have a problem and we should fix that first. But compliance requires deletion from online too. So if online fails, we should retry online. We don't want to do offline until online is done.
f. Return ACCEPTED.
2. Online Deletion Worker (could be part of the service above, but if we want to scale, we might have a separate worker that processes the enqueued jobs? But in step 1c we do online deletion in the request thread. That might be slow if we have many caches and online feature stores. We might want to make the request return quickly and have a separate online worker.
Alternatively, we can:
- The request thread only creates the DeletionRequest and enqueues an online deletion job (and then returns ACCEPTED).
- Then an online worker picks up the job and does the cache and online feature store deletion.
Then the offline job is enqueued only after the online job succeeds.
This way, the request is fast.
So:
Step 1: API creates DeletionRequest (status: PENDING) and enqueues an "online-deletion" job (with user_id and deletion_request_id).
Step 2: Online worker processes the job:
- Does cache and online feature store deletion.
- Updates DeletionRequest: online_status = SUCCESS or FAILED.
- If SUCCESS, enqueues an "offline-deletion" job.
Step 3: Offline worker processes the job:
- Does offline deletion (or schedules it and then waits?).
- Updates DeletionRequest: offline_status = SUCCESS or FAILED.
Then the user can poll the status.
3. Offline Deletion Worker (or job) that does the actual offline deletion.
This seems scalable.
However, note: the offline deletion might be heavy and we might want to batch multiple user_ids. We can have the online worker enqueue offline jobs individually, and then the offline worker batches them (by collecting multiple jobs and then processing a batch). But then we need to update each DeletionRequest individually.
We can have:
The offline worker runs every 5 minutes and:
SELECT user_id FROM deletion_requests
WHERE online_status='SUCCESS' AND offline_status='PENDING'
LIMIT 1000
Then it processes these 1000 user_ids in one batch (by calling the offline feature store's batch delete API, or running one DELETE with IN clause).
Then it updates the offline_status for these 1000 records.
But note: if the batch fails, we might want to retry the whole batch? Or we can break the batch into smaller pieces? We can do:
Try to delete the batch. If it fails, we can retry the whole batch (with exponential backoff) a few times. If it still fails, we mark each as FAILED? But then we lose the batch.
Alternatively, we can do per-user in the offline worker even though it's less efficient? But if we have 1 million users, we run 1 million DELETE statements? That's too heavy.
We need to balance.
Given that offline deletion might be run on a data warehouse that can handle large deletes, we might do:
The offline worker runs a single DELETE statement for all pending users? But that might be a huge list and the query might be too long.
We can do:
We create a temporary table with the user_ids to delete (for this batch) and then:
DELETE FROM feature_table
WHERE user_id IN (SELECT user_id FROM temp_table)
This might be efficient if the temporary table is small and the feature_table is indexed on user_id.
We can do this for each feature table.
Then we update the deletion_requests for the user_ids in the batch to offline_status='SUCCESS' if the delete succeeded.
If the delete fails (for the entire batch) we retry.
We don't have per-user granularity in the offline deletion, but we do in the DeletionRequest table.
This is acceptable because we know that the batch deletion either succeeded for all or none. But what if the batch has 1000 user_ids and the delete succeeds for 999 and fails for 1 (because of a lock or something)? Then the entire delete might fail? In most databases, if one row causes an error (like a foreign key constraint) then the entire statement fails. But if it's just a lock, the entire statement might wait and then succeed? We don't know.
We might have to accept that the batch deletion is atomic: either all user_ids in the batch are deleted or none.
Then we update the DeletionRequest accordingly.
This means that if one user in the batch fails, we retry the whole batch. That might cause some users to be retried multiple times (if one user in the batch is problematic). But eventually, we might succeed for the others? Not necessarily because the problematic user might keep causing the batch to fail.
We can have a way to skip problematic users? But then we need to know which one caused the failure.
Given the complexity, we might have to run per-user in the offline deletion. But then we lose efficiency.
We might have to compromise:
We run per-user in the offline deletion for the first few attempts (say 3) and then if it fails, we mark that user as FAILED and move on? But then we have to run the offline worker more frequently.
Alternatively, we can have two modes:
Mode 1: Batch deletion (for users that are not problematic)
Mode 2: Per-user deletion (for users that failed in batch)
But that's complex.
Given the time, we might stick to per-user offline deletion and accept that it might be slow and resource-intensive. But if we have millions of users, we cannot run millions of DELETE statements.
We might have to rely on the feature store's ability to handle batch deletes.
Let's assume the offline feature store is built on a data lake (like Delta Lake) and we can run:
DELETE FROM feature_table WHERE user_id IN (list)
and it's efficient because of the data layout (partitioning by user_id, or Z-ordering by user_id). Then we can do batch deletes.
We design the offline worker to:
- Collect up to N user_ids (N=1000) that are pending.
- For each feature table, run a DELETE with the list of user_ids.
- Then update the DeletionRequest for all those user_ids to offline_status='SUCCESS' if the delete succeeded for all tables? Or we update per table? We don't track per table.
We assume that the feature store's delete operation deletes from all relevant tables? Or we have to specify the table?
We have a configuration of tables. So we delete from each table.
We can do:
for table in offline_tables:
try:
delete from table where user_id in (batch_user_ids)
except:
log and break
If all tables succeeded, then update all DeletionRequest in the batch to offline_status='SUCCESS'
else, update all to 'FAILED'
Then we move to the next batch.
This way, we batch the user_ids and run one DELETE per table per batch.
We assume that the batch size (1000) is acceptable for the data warehouse.
We can adjust the batch size based on the performance.
This seems a good compromise.
Now, let's write the code structure:
We'll have:
models.py (for the DeletionRequest model)
deletion_service.py (the HTTP API)
workers/online_worker.py
workers/offline_worker.py
deleters/cache_deleter.py (with implementations for Redis, etc.)
deleters/online_feature_store_deleter.py (with implementation for the online feature store)
deleters/offline_feature_store_deleter.py (with implementation for the offline feature store, which might run batch deletes)
We use a task queue (like Celery, RQ, or just a database table as a queue) to pass jobs between the API and the workers.
We can use Celery:
The API enqueues a task: online_deletion_task(user_id, deletion_request_id)
The online_worker (Celery worker) runs the task:
- Does cache and online feature store deletion.
- Updates DeletionRequest.online_status.
- If online_status is SUCCESS, enqueues offline_deletion_task(user_id, deletion_request_id)
The offline_worker (Celery worker) runs the task:
- But note: we want to batch the offline tasks. So we don't want to enqueue one task per user for offline.
Instead, the offline worker should not be triggered by a task per user. We should have a periodic task (like a cron) that runs the offline worker and processes a batch of users.
So:
The online_worker, when it succeeds, does not enqueue an offline task. Instead, it just sets the DeletionRequest.online_status='SUCCESS'. Then the offline worker (which runs every 5 minutes) will pick up all DeletionRequests with online_status='SUCCESS' and offline_status='PENDING' and process them in batches.
Then we don't need an offline_deletion_task. We have a periodic offline worker that runs and processes batches.
This seems better.
Steps:
API:
- Creates DeletionRequest (online_status='PENDING', offline_status='PENDING')
- Enqueues online_deletion_task(user_id, deletion_request_id)
online_deletion_task:
- Does cache and online feature store deletion.
- Updates DeletionRequest.online_status to 'SUCCESS' or 'FAILED'.
offline_worker (periodic):
- Every 5 minutes, run:
SELECT user_id, id FROM deletion_requests
WHERE online_status='SUCCESS' AND offline_status='PENDING'
ORDER BY created_at
LIMIT 1000
- Then for these user_ids, run the offline deletion (batch delete for each feature table).
- Then update the DeletionRequest.offline_status to 'SUCCESS' for all these user_ids (if the batch delete succeeded for all tables) or 'FAILED' if any error.
But note: if the batch delete fails, we might want to retry the same batch? We can leave them as 'PENDING' and they will be picked up again in the next run.
So we don't update to 'FAILED' immediately. We try a few times (by keeping them as 'PENDING') and then after X retries, we mark as 'FAILED'.
We can add a column: offline_retry_count.
Then in the offline worker:
batch = SELECT ... WHERE online_status='SUCCESS' AND offline_status='PENDING' AND offline_retry_count < 5 ...
Then if the batch delete succeeds, update offline_status='SUCCESS'.
If fails, update offline_retry_count = offline_retry_count + 1.
Then after 5 retries, mark as 'FAILED'.
This way, we have retry.
This seems robust.
Now, let's consider the cache and online feature store deletion in the online_worker:
We might have multiple caches and multiple online feature stores. We want to try all, and if any fails, we mark online_status='FAILED'? Or we try all and then if any fails, we mark as 'FAILED'? But we might have partial success? We want to be resilient: if one cache fails, we still try the others.
We can do:
errors = []
for cache in caches:
try:
cache.delete_user_data(user_id)
except Exception as e:
errors.append(str(e))
for online_fs in online_feature_stores:
try:
online_fs.delete_user_data(user_id)
except Exception as e:
errors.append(str(e))
if errors:
log errors and set online_status='FAILED'
else:
online_status='SUCCESS'
But note: if one cache fails, we still want to mark the whole online as failed? Because we want to retry the entire online deletion? We might want to retry only the failed ones? But we don't have per-system status.
We can have:
online_status:
- SUCCESS: all succeeded.
- PARTIAL_FAILURE: some failed.
- FAILED: all failed? Or we don't have that granularity.
But for the purpose of triggering offline, we only want to trigger if all online systems succeeded? Because if the cache failed, it's not the end of the world (caches are ephemeral) but if the online feature store failed, then the user's data is still in the online feature store and that's critical.
So we might define:
online_status = 'SUCCESS' only if all online systems (caches and online feature stores) succeeded.
If any online feature store fails, then we set online_status='FAILED' and we don't trigger offline.
If only caches fail, we might still set online_status='SUCCESS'? Because caches are less critical? But the requirement is to delete from caches too.
We want to delete from all. So if any cache or online feature store fails, we set online_status='FAILED' and we retry.
We can have a configuration that marks which systems are critical. But let's assume all are critical.
Then:
if any system fails, online_status='FAILED'
We can also have a separate metric for cache failures and feature store failures.
But for simplicity, we do:
overall_success = True
for system in all_online_systems:
try:
system.delete_user_data(user_id)
except:
overall_success = False
if overall_success:
online_status='SUCCESS'
else:
online_status='FAILED'
Then the offline worker only processes those with online_status='SUCCESS'.
This seems acceptable.
Now, let's write some pseudo-code for the offline_worker:
def offline_worker():
batch_size = 1000
# Get a batch of user_ids that need offline deletion
pending_requests = DeletionRequest.objects.filter(
online_status='SUCCESS',
offline_status='PENDING',
offline_retry_count__lt=5
).order_by('created_at')[:batch_size]
if not pending_requests:
return
user_ids = [req.user_id for req in pending_requests]
request_ids = [req.id for req in pending_requests]
# For each offline feature store table, delete the user_ids
for table in offline_tables:
try:
# We assume a function that deletes by a list of user_ids for the given table
delete_from_table(table, user_ids)
except Exception as e:
# If any table fails, we break and retry the whole batch later
log(f"Failed to delete from table {table}: {e}")
# Increment retry count for all requests in this batch
for req_id in request_ids:
DeletionRequest.objects.filter(id=req_id).update(
offline_retry_count=F('offline_retry_count') + 1
)
return
# If we succeeded for all tables, update all requests to offline_status='SUCCESS'
DeletionRequest.objects.filter(id__in=request_ids).update(offline_status='SUCCESS')
But note: what if the delete_from_table deletes only some of the user_ids? We assume that the delete statement deletes all rows for the given user_ids. If a user_id doesn't exist in the table, that's fine (0 rows affected). We consider that a success.
However, if the table has millions of rows and the user_ids are scattered, the delete might be heavy. We assume that the data warehouse can handle it.
We might want to run the delete in a transaction? But for a data warehouse, we might not.
We'll leave that to the implementation of delete_from_table.
This is a high-level design.
We must also consider:
- Monitoring and alerting: if a deletion request is stuck in PENDING for too long, or if the offline worker fails repeatedly.
- We might need to delete from other systems (like data lake, S3, etc.) but the problem says caches and feature stores.
This design should work for the stated requirements.
Let me know if you have any questions or if you want to focus on a specific part.
I'll design a comprehensive data deletion compliance workflow that propagates user deletion requests through caching layers and feature stores while maintaining auditability, idempotency, and performance.
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Client/API │───▶│ Deletion │───▶│ Primary │
│ Request │ │ Orchestrator │ │ Database │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────────┐
│ Propagation │
│ Layer │
└─────────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
┌───────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Cache │ │ Feature │ │ Audit │
│ Layer │ │ Store │ │ Log │
│ (Redis/Mem) │ │ (Online/ │ │ (Immutable) │
└───────────────┘ │ Offline) │ └─────────────────┘
└─────────────────┘
Core Components
1. Deletion Request Schema
class DeletionRequest:
request_id: UUID4
user_id: str # Primary identifier
deletion_scope: Enum['FULL', 'PARTIAL'] # Full account or specific data
requested_at: datetime
status: Enum['PENDING', 'IN_PROGRESS', 'COMPLETED', 'FAILED', 'PARTIAL']
priority: Enum['HIGH', 'NORMAL', 'LOW'] # GDPR requires 30-day SLA
verification_token: str # For user verification
metadata: dict # What data types to delete
created_by: str # User/admin/service
completed_at: Optional[datetime]
failure_reason: Optional[str]
2. Orchestrator Service
class DeletionOrchestrator:
def __init__(self):
self.idempotency_store = Redis(idempotency_ttl=30d)
self.request_tracker = DeletionRequestDB()
self.propagation_verifier = PropagationVerifier()
async def process_deletion_request(self, request: DeletionRequest):
"""Main entry point with idempotency guarantee"""
# 1. Idempotency check
if await self.idempotency_store.exists(request.request_id):
return await self.get_existing_status(request.request_id)
# 2. Validation & verification
if not await self.verify_request(request):
raise InvalidDeletionRequestError("Verification failed")
# 3. Create tracking record
await self.request_tracker.create(request)
# 4. Trigger propagation workflow
workflow_id = await self.start_propagation_workflow(request)
return {
"request_id": request.request_id,
"workflow_id": workflow_id,
"status": "ACCEPTED",
"estimated_completion": self.estimate_completion_time(request)
}
3. Propagation Workflow Engine
workflow: user_deletion_v1
steps:
- idempotency_check:
action: check_already_processed
on_skip: return_existing_status
- primary_db_deletion:
action: soft_delete_primary
tables:
- users (SET deleted_at = NOW())
- user_profiles (SET deleted_at = NOW())
- user_activity (ARCHIVE to history table)
compensation: restore_from_backup
timeout: 5m
- cache_invalidation:
parallel: true
steps:
- session_cache:
system: redis_cluster
pattern: "session:{user_id}:*"
action: delete_pattern
ttl_extension: false # Don't extend TTL on delete
- feature_cache:
system: redis_feature_cache
keys:
- "features:{user_id}:*"
- "embeddings:{user_id}:*"
action: delete_pattern
verification: post_delete_check
- api_response_cache:
system: cdn_edge_cache
purge_urls:
- "/api/v1/users/{user_id}/*"
- "/profile/{user_id}"
- feature_store_propagation:
online:
- action: delete_entities
store: feast_online
entity_keys: [{user_id: "123"}]
feature_views: ["user_features", "user_embeddings"]
timeout: 2m
verification: count_verification
offline:
- action: schedule_batch_deletion
store: databricks_feature_store
tables:
- "feature_store.user_features_daily"
- "feature_store.user_embeddings_hourly"
deletion_type: "soft" # Add is_deleted flag
job_params:
spark_job: "delete_user_data"
partition_filter: "user_id = '{user_id}'"
timeout: 24h
verification: post_job_validation
- downstream_systems:
- action: publish_event
topic: "user.deletion.requested"
payload:
user_id: "{user_id}"
request_id: "{request_id}"
timestamp: "{now}"
deletion_scope: "{scope}"
systems:
- analytics
- ml_serving
- notification_service
- recommendation_engine
- audit_logging:
- action: create_audit_record
store: immutable_audit_db
data:
request: "{full_request}"
propagation_steps: "{step_results}"
compliance_metadata:
gdpr_article: "17"
data_controller: "company.com"
verification_method: "double_opt_in"
- completion:
- update_request_status: COMPLETED
- send_notification:
to: user_email
template: "deletion_complete"
- purge_verification_token: true
4. Cache Deletion Strategies
A. Redis/Memcached Pattern-Based Deletion
class CacheDeleter:
async def delete_user_pattern(self, user_id: str, pattern: str):
"""Efficient pattern-based deletion with SCAN"""
async with redis.pipeline() as pipe:
cursor = 0
while True:
cursor, keys = await redis.scan(
cursor=cursor,
match=pattern.format(user_id=user_id),
count=1000
)
if keys:
pipe.delete(*keys)
if cursor == 0:
break
await pipe.execute()
# Verification: Check for any remaining keys
remaining = await redis.scan(
match=pattern.format(user_id=user_id),
count=1
)
return len(remaining[1]) == 0
B. Cache-Aside Invalidation
class CacheAsideInvalidator:
async def invalidate_user_cache(self, user_id: str):
"""Invalidate using known cache keys from registry"""
cache_keys = await self.cache_registry.get_keys_for_user(user_id)
for key in cache_keys:
await redis.delete(key)
# Update registry to prevent re-caching
await self.cache_registry.mark_user_deleted(user_id)
5. Feature Store Integration
Feast/Tecton Integration
class FeatureStoreDeleter:
async def delete_online_features(self, user_id: str):
"""Delete from online feature store"""
client = feast.Client()
# Get all feature views containing user entity
feature_views = await client.list_feature_views()
user_fvs = [fv for fv in feature_views
if 'user_id' in fv.entities]
for fv in user_fvs:
# Delete by entity key
await client.delete_entities(
entity_keys=[{"user_id": user_id}],
feature_view_name=fv.name
)
async def schedule_offline_deletion(self, user_id: str):
"""Schedule batch deletion for offline store"""
job = DatabricksJob(
job_id="delete_user_features",
parameters={
"user_id": user_id,
"tables": [
"feature_store.user_features",
"feature_store.user_temporal_features"
]
}
)
run_id = await job.submit()
return run_id
Data Warehouse Deletion (BigQuery/Snowflake)
-- Soft delete pattern for offline features
UPDATE feature_store.user_features_daily
SET
is_deleted = TRUE,
deleted_at = CURRENT_TIMESTAMP(),
deletion_request_id = '{request_id}'
WHERE user_id = '{user_id}'
AND deletion_request_id IS NULL;
-- Verification query
SELECT COUNT(*) as remaining_records
FROM feature_store.user_features_daily
WHERE user_id = '{user_id}'
AND is_deleted = FALSE;
6. Verification & Monitoring
class PropagationVerifier:
async def verify_deletion_completeness(self, user_id: str, request_id: str):
"""Comprehensive verification across all systems"""
checks = {
"primary_db": await self.verify_primary_db(user_id),
"caches": await self.verify_caches(user_id),
"online_feature_store": await self.verify_online_fs(user_id),
"offline_feature_store": await self.verify_offline_fs(user_id),
"downstream_systems": await self.verify_downstream(user_id)
}
all_verified = all(checks.values())
# Log verification results
await self.audit_logger.log_verification(
request_id=request_id,
user_id=user_id,
checks=checks,
timestamp=datetime.utcnow()
)
return all_verified, checks
7. Compensation & Retry Logic
class CompensationHandler:
async def handle_failed_deletion(self, request_id: str, step: str, error: str):
"""Handle partial failures with compensation"""
if step == "primary_db_deletion":
# Restore from backup if needed
await self.restore_from_backup(request_id)
elif step == "cache_deletion":
# Retry with exponential backoff
await self.retry_with_backoff(
request_id=request_id,
max_retries=3,
step=step
)
elif step == "feature_store":
# Mark for manual review if retries exhausted
await self.escalate_to_compliance_team(
request_id=request_id,
error=error
)
8. Monitoring & Alerting
metrics:
- deletion_request_count_total
- deletion_completion_time_seconds
- deletion_failure_rate
- cache_deletion_latency
- feature_store_deletion_latency
- verification_success_rate
alerts:
- name: deletion_stuck_pending
condition: deletion_request_status == "PENDING" AND age > 24h
severity: critical
- name: high_failure_rate
condition: deletion_failure_rate > 0.05 FOR 5m
severity: warning
- name: verification_failure
condition: verification_success_rate < 0.99
severity: warning
9. Audit Trail (Immutable)
class ImmutableAuditLogger:
async def log_deletion_event(self, event: DeletionEvent):
"""Write to immutable storage (WORM/S3 with object lock)"""
audit_record = {
"event_id": uuid4(),
"timestamp": datetime.utcnow().isoformat(),
"event_type": "USER_DELETION",
"request_id": event.request_id,
"user_id": event.user_id,
"actor": event.actor,
"ip_address": event.ip_address,
"user_agent": event.user_agent,
"systems_affected": event.systems,
"verification_hash": self.calculate_hash(event),
"compliance_metadata": {
"gdpr_article": "17",
"data_subject_right": "erasure",
"verification_method": "double_opt_in"
}
}
# Write to multiple immutable stores
await self.s3_object_lock.write(audit_record)
await self.blockchain.hash_and_store(audit_record) # Optional
10. Idempotency & Exactly-Once Guarantees
class IdempotencyManager:
def __init__(self):
self.idempotency_store = Redis()
self.processing_locks = Redis()
async def acquire_lock(self, user_id: str, lock_ttl: int = 3600):
"""Prevent concurrent deletion of same user"""
lock_key = f"deletion_lock:{user_id}"
acquired = await self.idempotency_store.setnx(
lock_key,
"processing",
ex=lock_ttl
)
return acquired
async def mark_step_completed(self, request_id: str, step: str):
"""Track completed steps for recovery"""
step_key = f"deletion_step:{request_id}:{step}"
await self.idempotency_store.set(
step_key,
"completed",
ex=30*24*3600 # 30 days retention
)
async def get_completed_steps(self, request_id: str):
"""Recover from partial failures"""
pattern = f"deletion_step:{request_id}:*"
keys = await self.idempotency_store.scan(pattern)
return [key.split(":")[-1] for key in keys]
11. Configuration Management
deletion_workflow:
version: "1.0"
enabled: true
max_concurrent_deletions: 100
batch_size:
cache_deletion: 1000
feature_store_deletion: 500
timeouts:
primary_db: 300
cache: 60
feature_store_online: 120
feature_store_offline: 86400 # 24 hours
retry_policy:
max_attempts: 3
backoff_ms: [1000, 5000, 30000]
on_failure: " escalate_to_compliance"
verification:
required: true
methods:
- "post_deletion_check"
- "sample_audit"
sample_rate: 0.1 # Sample 10% for audit
compliance:
gdpr_article: "17"
retention_period_days: 2555 # 7 years
audit_required: true
12. API Endpoints
# Deletion Request
POST /api/v1/compliance/deletions
{
"user_id": "user_12345",
"verification_token": "verified_token",
"scope": "full", # or partial with metadata
"metadata": {
"delete_activity_logs": true,
"delete_feature_data": true,
"delete_cache_only": false
}
}
# Status Check
GET /api/v1/compliance/deletions/{request_id}
# Bulk Operations (Admin only)
POST /api/v1/compliance/deletions/bulk
{
"user_ids": ["user1", "user2"],
"priority": "high",
"reason": "legal_request"
}
# Verification Report
GET /api/v1/compliance/deletions/{request_id}/verification
13. Deployment Considerations
- Rate Limiting: Prevent abuse with per-user/IP rate limits
- Circuit Breakers: Protect downstream systems during failures
- Observability: Distributed tracing across all systems
- Data Residency: Respect geographic data location constraints
- Encryption: Ensure data is encrypted at rest during deletion
- Backup Coordination: Exclude deleted users from backups after verification
14. Testing Strategy
# Integration test example
async def test_full_deletion_workflow():
# 1. Create test user with data in all systems
user_id = await setup_test_user()
await populate_feature_store(user_id)
await populate_caches(user_id)
# 2. Submit deletion request
request = await orchestrator.process_deletion_request(
user_id=user_id,
verification_token=verify_user_identity(user_id)
)
# 3. Wait for completion (with timeout)
status = await wait_for_completion(request.request_id, timeout=300)
# 4. Verify deletion across all systems
assert await verify_primary_db_deleted(user_id)
assert await verify_caches_deleted(user_id)
assert await verify_feature_store_deleted(user_id)
assert await verify_audit_log_created(request.request_id)
Key Design Decisions
- Two-Phase Deletion: Soft delete in primary DB first, then propagate to other systems
- Idempotency First: Every operation must be safely repeatable
- Progressive Verification: Verify after each major step, not just at end
- Compensation Design: Every action has a compensating action
- Observability Built-in: All steps logged with context for debugging
- Graceful Degradation: If feature store deletion fails, cache still cleared
- Compliance by Default: Audit trails immutable, retention policies enforced
Failure Modes & Handling
| Failure Point | Detection | Recovery |
|---|
| Network timeout | Circuit breaker | Retry with backoff |
| Partial cache deletion | Post-deletion scan | Retry failed keys |
| Feature store unavailable | Health check | Queue for retry later |
| Verification failure | Sampling check | Manual compliance review |
| Idempotency conflict | Lock contention | Wait + retry |
This workflow provides GDPR/CCPA compliance while maintaining system performance and reliability. The key is the orchestrator pattern with idempotent operations, comprehensive verification, and immutable audit trails.