We are going to design a data retention and erasure pipeline that handles:
- Cascading deletions (when a piece of data is marked for deletion, we need to delete all derived data that depends on it)
- Tombstones (marking data as deleted without immediately removing it, for a grace period)
- Verification (ensuring that the data has been properly deleted and that no remnants remain)
- Proofs (generating cryptographic proofs that the data has been deleted, possibly for compliance)
Steps:
-
Tombstone Creation:
- When a deletion request comes in, we don't immediately delete the data. Instead, we create a tombstone record.
- The tombstone record includes:
- The identifier of the data to be deleted.
- The timestamp of the deletion request.
- A retention period (how long to keep the tombstone before actual deletion, for grace period and audit).
- A list of dependent data (if known) that should also be deleted (or their own tombstones created).
-
Cascading:
- We need to propagate the deletion to all dependent data. This can be done by:
a. Having a dependency graph (or tree) of data. When a node is marked for deletion, we traverse the graph and mark all children (or dependents) for deletion as well.
b. Alternatively, if the system is designed such that data is stored in a way that dependencies are implicit (e.g., in a relational database with foreign keys with cascading delete), then the database can handle the cascade.
c. In a more complex system, we might have a service that knows the dependencies and can issue deletion commands for each dependent.
-
Tombstone Maintenance:
-
During the retention period, the tombstone is kept. The actual data might be kept or might be deleted immediately?
Option 1: Keep the actual data until the retention period ends, then delete it. (But then we have to keep the data for the retention period, which might be against the intention of deletion? Actually, the intention is to delete but with a grace period for recovery or audit. So we keep the data for the retention period, then delete.)
Option 2: Delete the actual data immediately but keep the tombstone for the retention period. Then we have no data, only the record that it was deleted.
-
We must decide:
- If we keep the data during the retention period, then we must ensure that the data is not accessible (quarantine) and that it is deleted at the end of the period.
- If we delete the data immediately, then we must have a way to prove that we had the data and then deleted it? But then we cannot recover. So for compliance, we might need to keep the data for a period? Actually, the retention period might be the time we are required to keep the tombstone (proof of deletion) but not the data.
-
Let's assume we want to delete the data as soon as possible, but we must keep a proof. So:
Step 1: Create tombstone.
Step 2: Immediately delete the data (and all cascaded data) and record the deletion in the tombstone (with timestamp of actual deletion).
Step 3: Keep the tombstone for the retention period (for audit and proof generation).
-
However, if we delete the data immediately, then we cannot recover. So if there's a chance of mistake, we might want to keep the data for a short grace period (like 24 hours) and then delete. This is a business decision.
-
Verification:
-
We need to verify that the data has been deleted. This can be done by:
a. Checking that the data is no longer accessible via normal APIs.
b. Checking that the storage locations (files, database records, etc.) have been removed.
c. For distributed systems, we might need to check multiple nodes.
-
We can run a verification process after the deletion (or at the end of the retention period) to ensure that all copies are gone.
-
Proofs:
-
We want to generate a cryptographic proof that the data was deleted. This could be:
a. A signed statement from the system that the data with a given hash was deleted at a given time.
b. A proof that we have deleted all the data by showing that we have deleted the keys (if using encryption) and that the encrypted data is unrecoverable.
-
One common method is to use a Merkle tree of the data and then destroy the root key. But that's for encrypted data.
-
Alternatively, we can have a log (append-only) of deletion events. We can sign the log entries and then provide a proof that the deletion event is in the log.
-
We might also use a zero-knowledge proof that we have deleted the data without revealing the data? That's more advanced.
-
For simplicity, we can have a deletion log (tombstones) that is stored in an immutable storage (like a blockchain or an append-only log with signatures). Then we can provide a proof that a particular deletion event is recorded.
-
System Design:
Let's break down the components:
-
Challenges:
-
Distributed Systems: If the data is distributed, we must ensure deletion from all nodes. We might need a coordination mechanism (like a distributed transaction or a two-phase commit for deletion?).
-
Immutability: If we have immutable storage (like a blockchain or WORM storage) then we cannot delete. In that case, we might delete the keys and prove that the keys are gone.
-
Backups: We must ensure that backups are also purged. This might require a separate process to remove from backups.
-
Replication: If the data is replicated, we must delete from all replicas.
-
Audit Trails: We might have audit logs that contain the data. We must also delete from audit logs? Or we must redact? This is complex.
-
Implementation Steps:
Let's outline a simple implementation in a relational database and file storage:
Tables:
Table tombstones:
id (UUID, primary key)
data_id (string, the original data identifier)
deletion_request_time (timestamp)
actual_deletion_time (timestamp, nullable)
retention_period (interval, e.g., 30 days)
status (enum: 'requested', 'in_progress', 'deleted', 'verified', 'archived')
data_hash (string, optional: hash of the data at the time of deletion, for proof)
proof (text, nullable: the cryptographic proof or a reference to it)
Table tombstone_dependencies:
tombstone_id (UUID, foreign key to tombstones.id)
dependent_tombstone_id (UUID, foreign key to tombstones.id)
(This table records the cascade: for a tombstone, which other tombstones are its dependents)
Steps:
a. When a deletion request comes for data_id = 'A':
BEGIN TRANSACTION;
Insert into tombstones (id, data_id, deletion_request_time, retention_period, status)
VALUES (gen_random_uuid(), 'A', now(), '30 days', 'requested');
Let @tombstone_id = the generated id.
-- Now, find the dependencies of 'A' (from a dependency table or by querying the application's metadata)
-- For each dependent data_id (say 'B', 'C'):
Insert into tombstones (id, data_id, deletion_request_time, retention_period, status)
VALUES (gen_random_uuid(), 'B', now(), '30 days', 'requested');
Let @tombstone_id_B = the generated id.
Insert into tombstones_dependencies (tombstone_id, dependent_tombstone_id)
VALUES (@tombstone_id, @tombstone_id_B);
-- Similarly for 'C'
COMMIT;
Then, we publish an event (or have a background worker) that picks up tombstones with status 'requested' and starts the erasure process.
b. Erasure process for a tombstone:
For each tombstone in status 'requested':
1. Change status to 'in_progress'.
2. Delete the actual data (from database, file system, etc.) for the data_id.
3. Update the tombstone: set actual_deletion_time = now(), status = 'deleted'.
4. Then, for each dependent in tombstones_dependencies, if the dependent tombstone is still in 'requested', we might want to also start its erasure? Or we wait for the dependent to be picked up by the erasure process?
We can design so that when we create the dependent tombstones, we also set their status to 'requested'. Then the erasure process will pick them up independently.
However, note: the dependent data might not be accessible until the parent is deleted? Actually, we are deleting the parent and then the child. But if the child is independent, we can delete in any order? But if there are foreign keys, we must delete the child first? Actually, in a cascade delete in a database, we delete the children first then the parent. So we need to be careful about the order.
Alternatively, we can do:
- When we create the tombstones, we set the status of the dependents to 'requested' only after the parent is deleted? But that would be sequential.
Let's think:
Option: We create all tombstones at once and set them all to 'requested'. Then the erasure process can pick them up in any order? But if we try to delete a child that has a foreign key to the parent, and the parent is not yet deleted, then the child deletion might fail? So we must delete the child first? Actually, in a cascading delete in a database, we delete the children first then the parent. So we need to know the order.
We can store the dependency graph and then do a topological sort to determine the deletion order.
Alternatively, we can disable the foreign key constraints and then delete in any order? Not safe.
Better: We store the dependency graph and then when we are about to delete a tombstone, we check if all its parents (the data that depends on this data? Actually, in a foreign key, the child depends on the parent. So if we delete the parent, we must delete the child first. So the child is a dependent of the parent.
So when we have a deletion request for parent P, we create tombstones for P and all its children (and grandchildren, etc.). Then we must delete in reverse order (children before parent).
So we can:
- When creating tombstones, we traverse the dependency graph and assign a level (or order) to each. Then we set the status of the ones with the highest level (the leaves) to 'requested' first? But we create all at once.
Alternatively, we can have a queue of tombstones to delete. We start with the leaves (the ones that have no dependents in the set of tombstones we are deleting) and then move up.
How about:
Step 1: Build the set S of all data that will be deleted (the root and all dependents).
Step 2: Build the dependency graph for S (only within S). Then do a topological sort to get the deletion order (from leaves to root).
Step 3: Create tombstones for all in S, but set the status of the ones that are first in the deletion order to 'requested'? But then we have to wait for the first to be deleted before the next?
Alternatively, we can create all tombstones and then have a separate process that looks at the dependency graph and only deletes a tombstone when all its children (in the set S) are already deleted? That would be complex.
Simpler: We create all tombstones and set them all to 'requested'. Then, when the erasure process picks a tombstone, it checks if there are any other tombstones in S that are its children and are not yet deleted? Then it waits?
This is getting complex.
Let's assume that our data model does not have circular dependencies and that we can delete in any order by first removing the foreign key constraints? That's not safe.
Alternatively, we can design the erasure process to delete in the correct order by using the dependency graph:
- We have a table `tombstone_dependencies` that records: for a tombstone (parent), which tombstones are its dependents (children). But note: in a foreign key, the child depends on the parent. So if we delete the parent, we must delete the child first. So the child is a dependent of the parent? Actually, the child is a dependent because it references the parent. So when we delete the parent, we must delete the child. So the child is a dependent of the parent.
So the dependency graph:
parent (P) has a child (C) -> edge from P to C? Or from C to P?
Let's define:
If data C depends on data P (C has a foreign key to P), then when we delete P, we must delete C. So C is a dependent of P.
So we can say:
P -> C (P has a dependent C)
Then the deletion order must be: delete C first, then P.
So we need to delete in reverse order of the dependency graph (from leaves to root). The leaves are the data that have no dependents (in the set S).
How to implement:
We can have a `tombstone_dependencies` table that records:
parent_tombstone_id (the one that is being deleted, and its data is depended upon by the child)
child_tombstone_id (the one that depends on the parent)
Then, when we want to delete a tombstone, we check if there are any child_tombstones (in the set S) that are not yet deleted? If yes, we cannot delete this parent until the children are deleted.
So the erasure process:
For each tombstone with status 'requested', check if there are any child tombstones (in `tombstone_dependencies` where parent_tombstone_id = this tombstone_id) that are not in status 'deleted'. If there are, then skip this one for now (or set to waiting?).
But then we might have a deadlock? We need to start with the leaves. So we can:
- Find all tombstones that have no children (in the set S) and set them to 'requested'? But we already set all to 'requested'.
Alternatively, we can change the status to 'requested' only when it's safe to delete? But then we have to set the status of the leaves to 'requested' first, then when they are deleted, we set the parent to 'requested'? That would require a trigger.
Let's do:
Step 1: Build the set S and the dependency graph for S.
Step 2: Find the leaves (nodes with no children in S). For each leaf, set the tombstone status to 'requested' (if it's not already).
Step 3: The erasure process picks up 'requested' tombstones and deletes them. After deleting a tombstone, we check its parents (the ones that have this tombstone as a child) and if all the children of that parent are deleted, then set that parent's status to 'requested'.
This is a classic topological sort deletion.
We can implement this with a trigger on the tombstone table when a tombstone is marked as 'deleted':
For each parent_tombstone_id in `tombstone_dependencies` where child_tombstone_id = this deleted tombstone:
Check if all children of parent_tombstone_id are deleted (by counting the children that are not deleted). If none, then update the parent_tombstone set status = 'requested' where id = parent_tombstone_id and status is not 'deleted' (and maybe not 'requested' already?).
But we have to be careful of multiple children and concurrent deletions.
Alternatively, we can have a background job that periodically checks for tombstones that are ready to be deleted (i.e., all their children are deleted) and sets their status to 'requested'.
Let's do:
We have a column `remaining_children_count` in the tombstone table? Or we can compute on the fly.
We can have:
Table `tombstone`:
...
remaining_children_count (integer, default 0) -> the number of children (in the set S) that are not yet deleted.
Then, when we create the tombstones and the dependency edges:
For each tombstone in S (except the leaves), set `remaining_children_count` to the number of children it has in S.
Then, when we delete a child, we decrement the `remaining_children_count` of its parent. When it becomes 0, we set the parent's status to 'requested'.
Steps:
a. Build set S and the dependency graph (only within S).
b. For each node in S, set remaining_children_count = number of children in S.
c. For each node that has remaining_children_count = 0, set status = 'requested'.
Then, the erasure process:
- Pick a tombstone with status 'requested' and no remaining_children_count? Actually, we set status to 'requested' only when remaining_children_count=0. So when we pick a 'requested', we can delete it.
After deleting the tombstone (data), we set its status to 'deleted' and then:
For each parent in `tombstone_dependencies` where child_tombstone_id = this tombstone:
UPDATE tombstones
SET remaining_children_count = remaining_children_count - 1
WHERE id = parent_tombstone_id;
Then, if the parent's remaining_children_count becomes 0, set the parent's status to 'requested'.
This way, we ensure that we delete in the correct order.
But note: what if the parent is not in set S? Actually, we are only considering the set S (the cascade). The parent might be outside S? No, because we are only cascading within the set S. The dependency graph we built is only for the set S. So if a child is in S, then its parent must also be in S? Not necessarily: the child might depend on a parent that is not being deleted? That would be a problem because we cannot delete the child without deleting the parent? Actually, if the child depends on the parent and we delete the child, then the parent remains and the foreign key would break? So we must also delete the parent?
Therefore, when we build the set S, we must include not only the direct dependents but also their parents? Actually, we are starting from the root and going down (to dependents). But in a foreign key, the child depends on the parent. So if we delete the parent, we must delete the child. So we are going from parent to child. But if we have a child that depends on a parent that is not in the initial set, then we must also delete that parent?
Let's reexamine:
We are asked to delete data A.
A has a child B (B depends on A). So we must delete B when we delete A.
B might have a child C (C depends on B). So we must delete C when we delete B.
So we are going down the dependency tree (from parent to child). But what if there is a cycle? Then we have a problem.
Also, what if there is a child that depends on multiple parents? Then we must delete all its parents?
Actually, in a relational database, if a child has multiple foreign keys, then it depends on multiple parents. So if we delete any of the parents, we must delete the child? That doesn't sound right. Actually, if we delete a parent, then the child's foreign key to that parent would break. So we must delete the child if we delete any of its parents? That would be a cascade on multiple foreign keys. But typically, we design so that the child is deleted only when all parents are deleted? Or we have a single parent?
This is getting very complex.
Let's simplify:
We assume that the dependency is a tree (or a forest) and that each data item has at most one parent? That might not be true.
Alternatively, we can define the dependency as:
Data X depends on data Y if there is a foreign key from X to Y (and the foreign key is set to cascade on delete). Then when we delete Y, we must delete X.
So the direction: from Y (parent) to X (child).
Then, when we are asked to delete Y, we must delete all X that depend on Y (and then recursively).
So we are going down from Y to its children, then to their children, etc.
Then, the set S is all the descendants of Y (including Y) in the dependency graph.
Then, the deletion order must be: delete the leaves first (the ones that have no children in S), then their parents, etc.
So we build the subtree rooted at Y and then do a post-order traversal (children before parent).
So in our algorithm:
Given a root R (the data we are asked to delete):
Step 1: Find all descendants of R (including R) in the dependency graph. Let S be that set.
Step 2: For each node in S, we create a tombstone.
Step 3: Build the dependency edges only within S (i.e., for each edge from parent to child, if both parent and child are in S, then we record the edge).
Step 4: For each node in S, set `remaining_children_count` to the number of children it has in S.
Step 5: For each node in S that has `remaining_children_count` = 0, set its status to 'requested'.
Step 6: The erasure process deletes the tombstones with status 'requested' and then updates the parents as described.
This should work for a tree (or a DAG without cycles). If there is a cycle, then we will have nodes that never get their `remaining_children_count` to 0. So we must avoid cycles.
How to handle cycles? We can break the cycle by not cascading? Or we can treat the entire cycle as one unit? That's complex.
We assume no cycles.
-
Retention Period:
After the tombstone is verified, we keep it for the retention period (e.g., 30 days). Then we can archive it (move to cold storage) or delete it?
If we delete it, we lose the proof. So we might keep it forever? Or we might move it to a cheaper storage for long-term audit.
We can have a background job that, after the retention period, moves the tombstone to an archive table (or deletes it if not needed).
-
Implementation Considerations:
- The entire process is asynchronous and event-driven.
- We must handle failures: if the erasure fails, we must retry and alert.
- We must ensure that the tombstones are not deleted until the retention period and verification are done.
- We must have monitoring and alerting for stuck tombstones.
11. Example Code Structure (pseudocode):
We'll have:
- Tombstone model (with the fields above)
- DependencyService: to get the dependencies of a data_id (from a dependency registry or by querying the database foreign keys)
- DeletionRequestService: handles the API request, creates the root tombstone and then builds the cascade and creates all tombstones.
- ErasureService: a worker that picks up 'requested' tombstones and deletes the data, then updates the tombstone and triggers the parent check.
- VerificationService: a worker that picks up 'deleted' tombstones and verifies, then updates to 'verified'.
- ProofService: generates a proof for a given data_id (by looking up the tombstone and signing the record or providing a Merkle proof).
Steps for DeletionRequest:
def request_deletion(data_id):
# Check permissions, etc.
# Build the set S (all data to be deleted) and the dependency graph (within S).
S = [data_id]
graph = {} # parent -> list of children
queue = [data_id]
while queue:
current = queue.pop(0)
children = DependencyService.get_children(current) # get data that depend on current
for child in children:
if child not in S:
S.add(child)
queue.append(child)
# add edge current -> child
graph.setdefault(current, []).append(child)
# Now, create tombstones for all in S.
tombstones = {}
for d in S:
tombstone = Tombstone.create(data_id=d, status='created', remaining_children_count=0)
tombstones[d] = tombstone
# Now, for each node in S, set remaining_children_count to the number of children in S.
for node in S:
children_in_S = [child for child in graph.get(node, []) if child in S]
tombstones[node].remaining_children_count = len(children_in_S)
tombstones[node].save()
# Now, create the dependency edges in the database (tombstone_dependencies)
for parent, children in graph.items():
for child in children:
if child in S: # both in S
TombstoneDependency.create(parent_tombstone=tombstones[parent], child_tombstone=tombstones[child])
# Now, set the status of the leaves (remaining_children_count=0) to 'requested'
for node in S:
if tombstones[node].remaining_children_count == 0:
tombstones[node].status = 'requested'
tombstones[node].save()
Steps for ErasureWorker:
def run():
while True:
tombstone = Tombstone.objects.filter(status='requested').first()
if not tombstone:
sleep(1)
continue
try:
# Delete the actual data for tombstone.data_id
delete_data(tombstone.data_id) # this should delete from all storage systems
tombstone.actual_deletion_time = now()
tombstone.status = 'deleted'
tombstone.save()
# Now, update the parents
dependencies = TombstoneDependency.objects.filter(child_tombstone=tombstone)
for dep in dependencies:
parent = dep.parent_tombstone
# Decrement remaining_children_count
parent.remaining_children_count = parent.remaining_children_count - 1
parent.save()
if parent.remaining_children_count == 0:
parent.status = 'requested'
parent.save()
except Exception as e:
# log and retry later? or mark as failed?
tombstone.status = 'failed'
tombstone.save()
# alert
Steps for VerificationWorker:
def run():
while True:
tombstone = Tombstone.objects.filter(status='deleted').first()
if not tombstone:
sleep(1)
continue
try:
# Verify that the data is gone
if verify_deletion(tombstone.data_id):
tombstone.status = 'verified'
tombstone.save()
else:
# retry or alert
pass
except Exception as e:
# log
Proof generation:
def generate_proof(data_id):
tombstone = Tombstone.objects.get(data_id=data_id)
if tombstone.status not in ['deleted', 'verified']:
raise Exception("Data not yet deleted")
# We can sign the tombstone record with a private key.
# Or, if we have an append-only log, we can provide a proof of inclusion.
# Let's assume we sign the record:
message = f"{tombstone.data_id}:{tombstone.deletion_request_time}:{tombstone.actual_deletion_time}:{tombstone.data_hash}"
signature = sign(private_key, message)
proof = {
'tombstone_id': tombstone.id,
'data_id': tombstone.data_id,
'deletion_request_time': tombstone.deletion_request_time,
'actual_deletion_time': tombstone.actual_deletion_time,
'data_hash': tombstone.data_hash,
'signature': signature
}
return proof
12. Security:
- The private key for signing must be stored securely.
- The proof must be tamper-evident.
13. Scalability:
- For large cascades, we might have thousands of tombstones. We must ensure that the erasure and verification workers can handle the load.
- We might need to partition the work by data_id or by tombstone id.
14. Monitoring:
- Track the number of tombstones in each status.
- Track the time from request to deletion and to verification.
- Alert on failures.
15. Compliance:
- The retention period must be configurable and must comply with regulations.
- The proof must be acceptable to auditors.
16. Edge Cases:
- What if the data does not exist? We can still create a tombstone? Or we can return an error.
- What if the data is already deleted? We can check and then create a tombstone with status 'already_deleted'?
- What if the data is in a form that cannot be deleted (like immutable storage)? Then we must delete the keys and provide a proof of key deletion.
- What if the data is in a backup? We must have a process to remove from backups. This might be a separate system.
17. Conclusion:
This is a complex system. We have outlined a design that uses tombstones, cascading via a dependency graph, and a topological sort deletion order. We also have verification and proof generation.
We must adapt to the specific storage systems and compliance requirements.
Note: This design is for a relational database and file storage. For other storage systems (like distributed databases, object storage, etc.) the deletion mechanism will be different.
We assume that we have a way to enumerate dependencies (like a metadata table that stores foreign keys). In practice, we might need to query the database's information schema or have an application-level registry.
Also, the `delete_data` function must be implemented for each storage system.
This design is a starting point.</think>
I'll design a comprehensive data retention and erasure pipeline with all the components you've requested. This is a critical system for compliance (GDPR, CCPA, HIPAA) and security.
Architecture Overview
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Deletion │ │ Cascading │ │ Tombstone │
│ Request API │───▶│ Engine │───▶│ Manager │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Proof │ │ Verification │ │ Erasure │
│ Generator │◀───│ Engine │◀───│ Scheduler │
└─────────────────┘ └─────────────────┘ └─────────────────┘
1. Core Components
1.1 Tombstone Manager
-- Tombstone table structure
CREATE TABLE tombstones (
id UUID PRIMARY KEY,
entity_type VARCHAR(100) NOT NULL, -- 'user', 'document', 'transaction'
entity_id VARCHAR(255) NOT NULL, -- Original data identifier
deletion_requested_at TIMESTAMP NOT NULL,
deletion_scheduled_at TIMESTAMP NOT NULL, -- After retention period
deletion_completed_at TIMESTAMP,
retention_period_days INT NOT NULL, -- Legal retention requirement
cascade_depth INT DEFAULT 0, -- How many levels cascaded
proof_hash VARCHAR(64), -- Hash of deletion proof
status VARCHAR(20) DEFAULT 'active', -- active, scheduled, completing, completed, verified, failed
metadata JSONB, -- Additional context
CONSTRAINT unique_entity UNIQUE(entity_type, entity_id)
);
-- Dependency tracking
CREATE TABLE dependency_graph (
parent_id UUID REFERENCES tombstones(id) ON DELETE CASCADE,
child_id UUID REFERENCES tombstones(id) ON DELETE CASCADE,
relationship_type VARCHAR(50), -- 'parent-child', 'reference', 'derived'
depth INT NOT NULL,
PRIMARY KEY(parent_id, child_id)
);
1.2 Cascading Engine
class CascadingEngine:
def __init__(self, dependency_registry):
self.dependency_registry = dependency_registry # Maps entity types to dependency rules
async def cascade_delete(self, root_tombstone: Tombstone) -> List[Tombstone]:
"""
Recursively identify and create tombstones for all dependent data
"""
cascade_queue = [(root_tombstone, 0)]
created_tombstones = [root_tombstone]
while cascade_queue:
current, depth = cascade_queue.pop(0)
# Find all entities that depend on current entity
dependents = await self.find_dependents(current)
for dependent in dependents:
# Check if already tombstoned
existing = await self.get_existing_tombstone(dependent)
if existing:
continue
# Create new tombstone
new_tombstone = await self.create_tombstone(
entity_type=dependent.type,
entity_id=dependent.id,
retention_period=self.calculate_retention(dependent),
cascade_depth=depth + 1
)
# Record dependency relationship
await self.record_dependency(current.id, new_tombstone.id, depth + 1)
created_tombstones.append(new_tombstone)
cascade_queue.append((new_tombstone, depth + 1))
# Cascading limit check
if depth >= MAX_CASCADE_DEPTH:
logger.warning(f"Cascade depth limit reached for {dependent.id}")
break
return created_tombstones
async def find_dependents(self, tombstone: Tombstone) -> List[Entity]:
"""
Find all entities that reference or depend on the given entity
"""
dependents = []
# 1. Check foreign key relationships in database
db_dependents = await self.query_foreign_keys(tombstone.entity_type, tombstone.entity_id)
dependents.extend(db_dependents)
# 2. Check application-level dependencies
app_dependents = await self.dependency_registry.get_dependents(
tombstone.entity_type,
tombstone.entity_id
)
dependents.extend(app_dependents)
# 3. Check derived data (aggregates, indexes, materialized views)
derived = await self.find_derived_data(tombstone)
dependents.extend(derived)
return dependents
1.3 Erasure Scheduler
class ErasureScheduler:
def __init__(self, storage_adapters: Dict[str, StorageAdapter]):
self.storage_adapters = storage_adapters
self.erasure_queue = asyncio.Queue()
async def schedule_erasures(self):
"""
Continuously process tombstones scheduled for erasure
"""
while True:
# Get tombstones ready for erasure (past retention period)
ready_tombstones = await self.get_ready_tombstones()
for tombstone in ready_tombstones:
await self.erasure_queue.put(tombstone)
# Process erasures in parallel
tasks = []
for _ in range(MAX_CONCURRENT_ERASURES):
if not self.erasure_queue.empty():
tombstone = await self.erasure_queue.get()
tasks.append(self.erase_entity(tombstone))
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
await self.process_erasure_results(results)
await asyncio.sleep(ERASURE_CHECK_INTERVAL)
async def erase_entity(self, tombstone: Tombstone) -> ErasureResult:
"""
Execute actual data erasure across all storage systems
"""
start_time = datetime.utcnow()
storage_results = []
for adapter_name, adapter in self.storage_adapters.items():
try:
result = await adapter.erase(
entity_type=tombstone.entity_type,
entity_id=tombstone.entity_id
)
storage_results.append(result)
except Exception as e:
logger.error(f"Erasure failed on {adapter_name}: {e}")
storage_results.append(ErasureResult(
adapter=adapter_name,
success=False,
error=str(e)
))
# Check if all adapters succeeded
all_success = all(r.success for r in storage_results)
return ErasureResult(
tombstone_id=tombstone.id,
success=all_success,
storage_results=storage_results,
duration=datetime.utcnow() - start_time
)
1.4 Verification Engine
class VerificationEngine:
def __init__(self, verification_strategies: List[VerificationStrategy]):
self.strategies = verification_strategies
async def verify_erasure(self, tombstone: Tombstone) -> VerificationReport:
"""
Multi-method verification that data is truly gone
"""
report = VerificationReport(tombstone_id=tombstone.id)
for strategy in self.strategies:
try:
result = await strategy.verify(tombstone)
report.add_result(strategy.name, result)
except Exception as e:
report.add_result(strategy.name, VerificationResult(
success=False,
method=strategy.name,
error=str(e)
))
# Overall success if all strategies pass
report.overall_success = all(r.success for r in report.results)
return report
# Example verification strategies
class DatabaseVerification(VerificationStrategy):
async def verify(self, tombstone: Tombstone) -> VerificationResult:
"""Check that DB records are gone"""
# Query database directly (bypassing application layer)
count = await db.execute(
"SELECT COUNT(*) FROM {table} WHERE id = %s",
tombstone.entity_id
)
return VerificationResult(
success=(count == 0),
method="database_direct_query",
details={"remaining_records": count}
)
class LogVerification(VerificationStrategy):
async def verify(self, tombstone: Tombstone) -> VerificationResult:
"""Check access logs for any recent access attempts"""
recent_access = await audit_log.find_access(
entity_id=tombstone.entity_id,
since=tombstone.deletion_requested_at
)
return VerificationResult(
success=(len(recent_access) == 0),
method="audit_log_check",
details={"recent_access_count": len(recent_access)}
)
class StorageVerification(VerificationStrategy):
async def verify(self, tombstone: Tombstone) -> VerificationResult:
"""Verify physical storage is wiped (for SSDs, need cryptographic erase)"""
# Check if storage blocks are overwritten/encrypted keys destroyed
pass
1.5 Proof Generator
class ProofGenerator:
def __init__(self, private_key: bytes, notary_service: NotaryService = None):
self.private_key = private_key
self.notary_service = notary_service
async def generate_proof(self, tombstone: Tombstone) -> DeletionProof:
"""
Generate cryptographic proof of deletion
"""
# 1. Create proof payload
payload = {
"tombstone_id": str(tombstone.id),
"entity_type": tombstone.entity_type,
"entity_id": tombstone.entity_id,
"deletion_requested_at": tombstone.deletion_requested_at.isoformat(),
"deletion_completed_at": tombstone.deletion_completed_at.isoformat() if tombstone.deletion_completed_at else None,
"cascade_depth": tombstone.cascade_depth,
"retention_period_days": tombstone.retention_period_days
}
# 2. Sign the payload
payload_json = json.dumps(payload, sort_keys=True, separators=(',', ':'))
signature = self.sign_data(payload_json.encode())
# 3. Create Merkle proof if part of batch deletion
merkle_proof = None
if tombstone.batch_id:
merkle_proof = await self.create_merkle_proof(tombstone)
# 4. Optional: Notarize with third-party service
notary_receipt = None
if self.notary_service:
notary_receipt = await self.notary_service.notarize(payload_json, signature)
return DeletionProof(
tombstone_id=tombstone.id,
payload=payload,
signature=signature.hex(),
merkle_proof=merkle_proof,
notary_receipt=notary_receipt,
algorithm="RSA-PSS-SHA256",
generated_at=datetime.utcnow()
)
def sign_data(self, data: bytes) -> bytes:
"""Cryptographic signature"""
return rsa_sign(data, self.private_key, padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
), hashes.SHA256())
async def create_merkle_proof(self, tombstone: Tombstone) -> MerkleProof:
"""Create Merkle tree proof for batch deletions"""
# Get all tombstones in the same batch
batch_tombstones = await Tombstone.filter(batch_id=tombstone.batch_id)
# Build Merkle tree
hashes = [self.hash_tombstone(t) for t in batch_tombstones]
merkle_tree = MerkleTree(hashes)
# Get proof for this tombstone
index = batch_tombstones.index(tombstone)
return merkle_tree.get_proof(index)
2. Workflow Example
async def complete_deletion_pipeline(user_id: str):
"""
Full pipeline from request to proof generation
"""
# Step 1: Create root tombstone
root_tombstone = await Tombstone.create(
entity_type='user',
entity_id=user_id,
deletion_requested_at=datetime.utcnow(),
retention_period_days=30, # Legal requirement
status='active'
)
# Step 2: Cascade and create all dependent tombstones
cascade_engine = CascadingEngine(dependency_registry)
all_tombstones = await cascade_engine.cascade_delete(root_tombstone)
# Step 3: Schedule erasures (after retention period)
erasure_scheduler = ErasureScheduler(storage_adapters)
await erasure_scheduler.schedule_for_future(
tombstones=all_tombstones,
execute_at=root_tombstone.deletion_requested_at + timedelta(days=30)
)
# Step 4: Execute erasures when scheduled
erasure_results = await erasure_scheduler.process_ready_tombstones()
# Step 5: Verify all erasures
verification_engine = VerificationEngine(strategies)
verification_reports = []
for tombstone, erasure_result in zip(all_tombstones, erasure_results):
if erasure_result.success:
report = await verification_engine.verify_erasure(tombstone)
verification_reports.append(report)
# Update tombstone status
if report.overall_success:
tombstone.status = 'verified'
tombstone.deletion_completed_at = datetime.utcnow()
else:
tombstone.status = 'verification_failed'
# Step 6: Generate proofs
proof_generator = ProofGenerator(private_key, notary_service)
proofs = []
for tombstone in all_tombstones:
if tombstone.status == 'verified':
proof = await proof_generator.generate_proof(tombstone)
proofs.append(proof)
tombstone.proof_hash = proof.hash()
await tombstone.save()
return {
"root_tombstone_id": str(root_tombstone.id),
"total_cascaded": len(all_tombstones),
"erasure_success_rate": sum(r.success for r in erasure_results) / len(erasure_results),
"verification_success_rate": sum(r.overall_success for r in verification_reports) / len(verification_reports),
"proofs_generated": len(proofs),
"audit_trail_id": await self.generate_audit_trail(all_tombstones, proofs)
}
3. Storage Adapters Interface
class StorageAdapter(ABC):
@abstractmethod
async def erase(self, entity_type: str, entity_id: str) -> ErasureResult:
"""Erase data from specific storage system"""
pass
@abstractmethod
async def verify_erase(self, entity_type: str, entity_id: str) -> bool:
"""Verify data is erased from this storage"""
pass
class PostgresAdapter(StorageAdapter):
async def erase(self, entity_type, entity_id):
# Soft delete first (for audit)
await db.execute(
f"UPDATE {entity_type} SET deleted_at = NOW() WHERE id = %s",
entity_id
)
# Hard delete after verification period
await db.execute(
f"DELETE FROM {entity_type} WHERE id = %s",
entity_id
)
# Also delete from related tables
await self.cascade_sql_delete(entity_type, entity_id)
return ErasureResult(success=True, adapter="postgres")
async def cascade_sql_delete(self, entity_type: str, entity_id: str):
"""Execute SQL cascade based on FK constraints"""
# Get all tables with FK to this entity
fk_tables = await self.get_referencing_tables(entity_type)
for table in fk_tables:
await db.execute(
f"DELETE FROM {table} WHERE {entity_type}_id = %s",
entity_id
)
class S3Adapter(StorageAdapter):
async def erase(self, entity_type, entity_id):
# Find all objects with this entity in path
objects = await s3.list_objects(
Prefix=f"{entity_type}/{entity_id}/"
)
# Delete objects (S3 versioned buckets need special handling)
for obj in objects:
await s3.delete_object(Bucket=bucket, Key=obj['Key'])
# For versioned buckets, delete all versions
if bucket_versioned:
versions = await s3.list_object_versions(
Prefix=f"{entity_type}/{entity_id}/"
)
for v in versions['Versions']:
await s3.delete_object(
Bucket=bucket,
Key=v['Key'],
VersionId=v['VersionId']
)
return ErasureResult(success=True, adapter="s3")
class RedisAdapter(StorageAdapter):
async def erase(self, entity_type, entity_id):
# Delete all keys matching pattern
pattern = f"{entity_type}:{entity_id}:*"
keys = await redis.keys(pattern)
if keys:
await redis.delete(*keys)
return ErasureResult(success=True, adapter="redis")
4. Compliance & Audit Features
class AuditTrail:
def __init__(self, audit_db):
self.audit_db = audit_db
async def log_deletion_event(self, tombstone: Tombstone, action: str, operator: str):
"""Immutable audit log entry"""
entry = {
"timestamp": datetime.utcnow().isoformat(),
"tombstone_id": str(tombstone.id),
"entity_type": tombstone.entity_type,
"entity_id": tombstone.entity_id,
"action": action, # 'requested', 'cascaded', 'erased', 'verified', 'proved'
"operator": operator,
"cascade_depth": tombstone.cascade_depth,
"ip_address": self.get_request_ip(),
"user_agent": self.get_user_agent()
}
# Write to append-only audit log (could be Kafka, Lambda, etc.)
await self.audit_db.insert(entry)
# Also write to WORM storage if required
if REQUIRE_WORM:
await self.write_to_worm_storage(entry)
async def generate_compliance_report(self, date_range: DateRange) -> Dict:
"""Generate compliance report for auditors"""
report = {
"period": date_range,
"generated_at": datetime.utcnow().isoformat(),
"total_deletions": 0,
"cascade_stats": {},
"verification_stats": {},
"proofs_generated": 0,
"failures": []
}
entries = await self.get_audit_entries(date_range)
for entry in entries:
if entry['action'] == 'requested':
report['total_deletions'] += 1
# Track cascade depth distribution
depth = entry.get('cascade_depth', 0)
report['cascade_stats'][depth] = report['cascade_stats'].get(depth, 0) + 1
return report
5. Deployment & Monitoring
# docker-compose.yml for the pipeline
version: '3.8'
services:
deletion-api:
image: deletion-api:latest
environment:
- DEPENDENCY_REGISTRY_URL=${DEPENDENCY_REGISTRY_URL}
- AUDIT_DB_URL=${AUDIT_DB_URL}
depends_on:
- postgres
- redis
cascade-worker:
image: cascade-worker:latest
command: python -m workers.cascade_worker
environment:
- DATABASE_URL=${DATABASE_URL}
depends_on:
- deletion-api
erasure-scheduler:
image: erasure-scheduler:latest
command: python -m workers.erasure_scheduler
environment:
- DATABASE_URL=${DATABASE_URL}
- S3_BUCKET=${S3_BUCKET}
depends_on:
- postgres
verification-worker:
image: verification-worker:latest
command: python -m workers.verification_worker
environment:
- DATABASE_URL=${DATABASE_URL}
depends_on:
- erasure-scheduler
proof-service:
image: proof-service:latest
ports:
- "8080:8080"
environment:
- PRIVATE_KEY_PATH=/keys/private.pem
- NOTARY_SERVICE_URL=${NOTARY_SERVICE_URL}
volumes:
- ./keys:/keys
prometheus:
image: prom/prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
grafana:
image: grafana/grafana
ports:
- "3000:3000"
# prometheus.yml
scrape_configs:
- job_name: 'deletion_pipeline'
static_configs:
- targets: ['deletion-api:8080', 'cascade-worker:9090', 'erasure-scheduler:9091']
6. Key Metrics & Alerts
# Monitoring metrics to collect:
METRICS = {
"deletion_requests_total": "Counter of deletion requests by entity type",
"cascade_depth_histogram": "Distribution of cascade depths",
"erasure_duration_seconds": "Histogram of erasure times",
"verification_success_rate": "Gauge of verification success %",
"proof_generation_duration": "Histogram of proof generation times",
"tombstones_stuck_seconds": "Gauge of time tombstones spend in each status",
"storage_adapter_errors_total": "Counter of errors per storage adapter"
}
# Critical alerts:
ALERTS = {
"HighErasureFailureRate":
"rate(erasure_failures_total[5m]) / rate(erasures_attempted_total[5m]) > 0.05",
"TombstonesStuckInCompletion":
"sum(tombstones_status{status='completing'}[1h]) > 10",
"VerificationFailures":
"rate(verification_failures_total[5m]) > 1",
"CascadeDepthExceeded":
"histogram_quantile(0.99, cascade_depth_histogram) > 5"
}
7. Security Considerations
- Access Control: Strict RBAC for deletion requests (only authorized roles)
- Encryption: All sensitive data in transit (TLS 1.3) and at rest (AES-256)
- Key Management: Use HSM or cloud KMS for signing keys
- Network Segmentation: Pipeline components in private subnet
- Audit Immutability: Write-once-read-many (WORM) storage for audit logs
- Rate Limiting: Prevent DoS on deletion endpoints
- Input Validation: Sanitize all entity IDs to prevent injection
8. Recovery & Rollback
class RecoveryManager:
async def restore_from_tombstone(self, tombstone_id: UUID,
restore_window_hours: int = 24):
"""
Emergency restore within retention window
Requires special authorization and dual-control
"""
tombstone = await Tombstone.get(id=tombstone_id)
# Check if within restore window
if (datetime.utcnow() - tombstone.deletion_requested_at).hours > restore_window_hours:
raise Exception("Restore window expired")
# Check authorization (requires 2 approvers)
if not await self.check_multi_sign_approval(tombstone_id):
raise Exception("Insufficient approvals")
# Restore from backup
backup = await backup_system.find_latest_backup(
entity_type=tombstone.entity_type,
entity_id=tombstone.entity_id,
before=tombstone.deletion_requested_at
)
if backup:
await backup_system.restore(backup)
await self.log_recovery(tombstone_id, operator)
return True
return False
Implementation Roadmap
Phase 1 (Weeks 1-2): Core Infrastructure
- Set up database schema for tombstones and dependency graph
- Implement basic tombstone creation and scheduling
Phase 2 (Weeks 3-4): Cascading & Storage Adapters
- Implement dependency discovery
- Build adapters for primary storage systems (Postgres, S3, Redis)
Phase 3 (Weeks 5-6): Verification & Proofs
- Implement multi-strategy verification
- Build cryptographic proof generation with RSA/ECDSA
Phase 4 (Weeks 7-8): Compliance & Monitoring
- Set up immutable audit logging
- Create Grafana dashboards and alerts
Phase 5 (Weeks 9-10): Testing & Hardening
- Chaos testing (simulate failures)
- Security audit
- Performance testing at scale
Key Design Decisions
- Tombstones First: Always create tombstones before any actual deletion
- Cascade Limits: Prevent infinite cascades with configurable depth limits
- Retention Periods: Configurable per entity type based on legal requirements
- Verification Diversity: Multiple independent verification methods
- Proof Portability: Standards-based proofs (can be verified without our system)
- Immutable Audit: All actions logged to append-only storage
- Grace Periods: Configurable windows for recovery before hard deletion
This pipeline provides:
- Legal compliance with audit trails and proofs
- Technical assurance through multi-method verification
- Operational safety with cascading controls and recovery windows
- Scalability through async workers and queue-based processing
- Security with cryptographic proofs and strict access controls
Would you like me to elaborate on any specific component or provide more detailed implementation for a particular storage system?