
Data Retention Policies
- 66 installs
- 41 repo stars
- Updated March 13, 2026
- finsilabs/awesome-ecommerce-skills
Automate order and customer data lifecycle: archive old records, anonymize PII on request, and purge expired data on schedule.
About
Defines a documented retention schedule balancing tax-record obligations against GDPR data minimization, then automates archival, anonymization, and purging. A developer uses it for GDPR minimization, audit prep, or controlling data-storage growth.
- Retention-schedule (RoPA) table per data category with legal basis
- Distinguishes anonymization of financial records from account deletion and log purging
Data Retention Policies by the numbers
- 66 all-time installs (skills.sh)
- Ranked #1,203 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/finsilabs/awesome-ecommerce-skills --skill data-retention-policiesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 66 |
|---|---|
| repo stars | ★ 41 |
| Last updated | March 13, 2026 |
| Repository | finsilabs/awesome-ecommerce-skills ↗ |
What it does
Automate order and customer data lifecycle: archive old records, anonymize PII on request, and purge expired data on schedule.
Files
Data Retention Policies
Overview
Data retention policies define how long each category of data is kept, when it is archived, and when it is purged. E-commerce stores must balance legal obligations (tax records must typically be kept 5–7 years) against privacy regulations (GDPR's data minimization principle requires deleting data that is no longer needed). The right approach depends on your platform — Shopify handles some retention automatically, while WooCommerce/custom stores require explicit implementation.
When to Use This Skill
- When implementing GDPR data minimization requirements for a new or existing e-commerce platform
- When legal or compliance teams request a documented data retention policy
- When preparing for a data protection audit or SOC 2 Type II assessment
- When storage costs are growing due to uncontrolled data accumulation
- When a customer submits a Subject Access Request and you need to know exactly where their data lives
Core Instructions
Step 1: Document your retention schedule first
Before configuring any tool, document a retention schedule. Legal, compliance, and engineering must agree before implementation. This Register of Processing Activities (RoPA) is required under GDPR Article 30 for large processors and recommended for all:
| Data Category | Retention Period | Action After Period | Legal Basis |
|---|---|---|---|
| Orders (financial records) | 7 years | Anonymize PII; keep financial data | Tax law (US IRS, EU VAT) |
| Invoices | 7 years | Archive to cold storage | Tax compliance |
| Customer accounts | 3 years after last activity | Delete | Legitimate interest |
| Sessions / login logs | 90 days | Delete | Legitimate interest |
| Marketing email consent | Until unsubscribe | Delete on unsubscribe | GDPR consent |
| Abandoned cart data | 30 days | Delete | Legitimate interest |
| Fraud/security logs | 90 days | Anonymize | Legitimate interest |
| Analytics events | 13 months | Aggregate then delete | Legitimate interest |
Key principle: Never delete what the law requires you to keep. For orders, anonymize the customer's PII (name, email, address) while preserving the financial record (amounts, tax, payment method brand/last 4).
Step 2: Platform-specific retention configuration
---
Shopify
Shopify stores order data indefinitely by default and handles platform-level data retention for infrastructure components.
Customer data export and deletion (GDPR compliance): Shopify provides built-in GDPR webhooks: 1. Go to Settings → Customers → Customer privacy 2. Shopify automatically sends customers/data_request and customers/redact webhooks to any installed apps when a customer requests their data or deletion 3. For your own app or custom code, register webhook handlers for these events
Manual customer anonymization: 1. Open a customer record → More actions → Anonymize this customer 2. Shopify replaces PII with anonymized placeholders while keeping order records 3. This is irreversible — confirm before proceeding
Automated email list cleanup: Use Klaviyo (or your email provider) to automatically suppress or delete contacts who haven't opened an email in 12+ months. Most email providers have "sunset" automation features built in.
Data export for archiving: 1. Go to Customers → Export to download customer data as CSV for archival 2. For orders: Orders → Export 3. Store exports in encrypted cold storage (e.g., AWS S3 with Glacier lifecycle policy)
---
WooCommerce
WooCommerce does not enforce data retention automatically. You need to configure it via plugins and scheduled tasks.
WooCommerce's built-in cleanup: 1. Go to WooCommerce → Status → Tools 2. Use Clean up WooCommerce sessions to delete expired session data 3. Use WooCommerce tracker cleanup to clear tracking data
GDPR / data retention plugin: Install WP GDPR Compliance or GDPR Cookie Consent (by WebToffee): 1. Go to WP GDPR Compliance → Settings → Data Retention 2. Configure retention periods per data type 3. The plugin creates scheduled cleanups via WP-Cron
Manual scheduled cleanup (WP-Cron):
// Add to your theme's functions.php or a custom plugin
// Schedule a daily cleanup job
if (!wp_next_scheduled('wc_data_retention_cleanup')) {
wp_schedule_event(time(), 'daily', 'wc_data_retention_cleanup');
}
add_action('wc_data_retention_cleanup', 'run_data_retention');
function run_data_retention() {
// Delete WooCommerce sessions older than 90 days
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->prefix}woocommerce_sessions WHERE session_expiry < %d",
time() - (90 * DAY_IN_SECONDS)
)
);
// Log the cleanup
error_log('WC data retention: cleaned sessions older than 90 days');
}Order PII anonymization for tax compliance: Do not delete orders (required for tax records). Instead, anonymize PII while keeping financial data. Install WooCommerce GDPR (WebToffee) which adds an "Anonymize" action to orders.
---
BigCommerce
BigCommerce provides customer data management tools in the admin panel.
Customer data export: 1. Go to Customers → Export → All Customers (CSV) 2. Use for archival before deleting customer accounts
Customer deletion: 1. Go to Customers → find the customer → Delete 2. BigCommerce retains associated order records when a customer account is deleted
Automated retention: BigCommerce does not have built-in scheduled data retention. Use the BigCommerce Customers API and Orders API to: 1. Query customers inactive for more than 3 years 2. Archive their data 3. Delete or anonymize their accounts
This requires a custom script or a third-party integration (e.g., via Zapier or a custom app).
---
Custom / Headless
For custom storefronts, implement automated purge and anonymization jobs that run on a schedule.
Key principle: batch small, run off-peak, always log:
// Run nightly at 2 AM UTC
import { CronJob } from 'cron';
new CronJob('0 2 * * *', runRetentionJobs).start();
async function runRetentionJobs() {
const jobs = [
{ name: 'purge_sessions', fn: purgeSessions },
{ name: 'purge_abandoned_carts', fn: purgeAbandonedCarts },
{ name: 'anonymize_old_orders', fn: anonymizeOldOrders },
{ name: 'purge_inactive_customers', fn: purgeInactiveCustomers },
];
for (const job of jobs) {
try {
const result = await job.fn();
await db.retentionAuditLog.insert({ job: job.name, ...result, runAt: new Date() });
} catch (err) {
await alertOps(`Retention job failed: ${job.name}`, err);
}
}
}
// Paginated delete — avoids table locks
async function purgeSessions(): Promise<{ deleted: number }> {
const cutoff = new Date(Date.now() - 90 * 86400_000);
let deleted = 0;
while (true) {
const batch = await db.sessions.findExpired(cutoff, { limit: 1000 });
if (batch.length === 0) break;
await db.sessions.deleteBatch(batch.map(s => s.id));
deleted += batch.length;
await new Promise(r => setTimeout(r, 100)); // yield between batches
}
return { deleted };
}
// Anonymize order PII but keep financial data (7-year tax requirement)
async function anonymizeOldOrders(): Promise<{ anonymized: number }> {
const cutoff = new Date(Date.now() - 7 * 365 * 86400_000);
const orders = await db.orders.findWhere({ created_at: { lt: cutoff }, pii_anonymized_at: null }, { limit: 500 });
for (const order of orders) {
await db.orders.update(order.id, {
customer_email: `anon_${order.id}@deleted.invalid`,
customer_name: 'Anonymous Customer',
shipping_name: 'Anonymous',
shipping_street: null,
shipping_city: order.shipping_city, // Keep for tax jurisdiction
shipping_country: order.shipping_country,
billing_name: 'Anonymous',
billing_street: null,
// Financial data (total_amount, tax_amount, payment_method_last4): UNCHANGED
pii_anonymized_at: new Date(),
});
}
return { anonymized: orders.length };
}Cross-service customer deletion: When deleting a customer, purge data from every system that holds it:
async function purgeCustomer(customerId: string, reason: 'gdpr_request' | 'inactivity') {
// 1. Anonymize orders (keep for tax, remove PII)
await anonymizeOrdersForCustomer(customerId);
// 2. Delete from email platform (Klaviyo, Mailchimp)
await emailPlatform.deleteContact(customerId);
// 3. Delete from search index (Algolia, Elasticsearch)
await searchIndex.deleteCustomer(customerId);
// 4. Delete analytics identifier
await analytics.deleteUser(customerId);
// 5. Delete the customer profile
await db.customers.anonymize(customerId);
// 6. Log for compliance evidence
await db.retentionAuditLog.insert({ action: 'customer_purged', customerId, reason, executedAt: new Date() });
}Best Practices
- Document before implementing — legal, compliance, and engineering must agree on the retention schedule; unilateral engineering decisions create compliance gaps
- Anonymize financial records, never delete them — orders must be retained for the tax statutory period; replace PII fields with anonymized placeholders
- Keep a separate, append-only retention audit log — this is your evidence for compliance auditors; never delete from this log
- Run purge jobs in small batches off-peak — use
SELECT ... LIMIT nbatches to avoid table locks that impact live traffic - Handle cross-service deletion as a checklist — purges spanning multiple services (database, email platform, analytics) must be resilient; log completion for each system separately
- Respond to GDPR deletion requests within 30 days — build automated workflows with reminders and escalations; track all requests with deadlines
Common Pitfalls
| Problem | Solution |
|---|---|
| Retention job locks production tables | Use small batch sizes (500–5000 rows), add LIMIT to every DELETE/UPDATE, run during low-traffic hours |
| Purging customers with open disputes or pending orders | Check for pending chargebacks, open orders, and active subscriptions before any purge; implement a legal hold mechanism |
| Forgetting search indexes and analytics warehouses | Maintain a registry of all systems that store personal data; include each in every deletion workflow |
| GDPR deletion request not completed within 30 days | Build an automated workflow with a 30-day deadline tracker; escalate to a human if not completed 5 days before the deadline |
| Backup systems containing data past retention period | Flag purged customer IDs so that if a backup is restored for disaster recovery, those records are immediately re-purged |
Related Skills
- @gdpr-ecommerce
- @account-security
- @financial-audit-trail
- @financial-compliance-sox
{
"context": "Tests whether the agent implements a complete GDPR customer purge with a legal hold check, deletes from all required satellite systems in the correct order, uses a saga/checklist pattern for resilience, logs the purge action to the retention audit log, and includes a 30-day deadline tracking mechanism.",
"type": "weighted_checklist",
"checklist": [
{
"name": "Legal hold check",
"max_score": 10,
"description": "Function checks for an active legal hold before proceeding with any deletion, and throws an error (or returns an error) if a hold is found"
},
{
"name": "Primary DB deletion",
"max_score": 8,
"description": "Function deletes or anonymizes the customer's data from the primary database (profile deletion AND order anonymization)"
},
{
"name": "Search index deletion",
"max_score": 8,
"description": "Function deletes the customer from a search index (Elasticsearch, Algolia, or equivalent)"
},
{
"name": "Analytics platform deletion",
"max_score": 8,
"description": "Function deletes the customer from an analytics service (analytics.deleteUser or equivalent)"
},
{
"name": "Email platform deletion",
"max_score": 8,
"description": "Function removes the customer from an email marketing platform (emailPlatform.deleteContact or equivalent)"
},
{
"name": "CDN cache purge",
"max_score": 7,
"description": "Function purges the customer's cached pages from a CDN (cdn.purgePrefix('/account/{customerId}') or equivalent)"
},
{
"name": "Backup exclusion flag",
"max_score": 7,
"description": "Function flags the customer ID in the backup system for exclusion from restores (backupSystem.excludeFromRestore or equivalent)"
},
{
"name": "Saga/checklist pattern",
"max_score": 10,
"description": "Function maintains a log or checklist (array, map, or DB record) of which systems have been successfully purged — enabling partial failure recovery"
},
{
"name": "Retention audit log entry",
"max_score": 8,
"description": "Function records the purge event in a retention audit log (db.retentionAuditLog.insert or equivalent) including the reason and systems purged"
},
{
"name": "Reason parameter typed",
"max_score": 6,
"description": "The reason parameter is typed or documented with at least these values: 'gdpr_request', 'inactivity', 'account_closure'"
},
{
"name": "30-day deadline tracking",
"max_score": 10,
"description": "DESIGN.md or code describes a mechanism to track GDPR deletion requests with deadlines (a table with request date + deadline, or automated reminders/escalations)"
},
{
"name": "No deletion without hold check",
"max_score": 10,
"description": "Code does NOT proceed to any deletion step if the legal hold check has not been performed first (hold check appears before any delete/purge call)"
}
]
}
Customer Right-to-Erasure Implementation
Problem/Feature Description
Your company's data protection officer has received an uptick in GDPR "right to erasure" (Article 17) requests from customers asking to have their accounts deleted. The current process is entirely manual: someone on the team finds the customer in the database and deletes their profile row, but this often misses data in the search index, email marketing platform, analytics warehouse, and CDN-cached pages. Auditors flagged this as a gap because there is no evidence the deletions were actually completed across all systems.
The engineering team needs to build a TypeScript function purgeCustomerData that handles the full deletion workflow for a single customer. The function must be resilient: if it is interrupted halfway through (e.g. the analytics API times out), it should be possible to tell which systems were already cleaned and which still need work. The function also needs to handle edge cases — for example, a customer who has an unresolved chargeback dispute cannot be legally deleted yet.
Additionally, the team needs a lightweight mechanism to track incoming erasure requests so that nothing falls through the cracks past the statutory deadline.
Output Specification
Produce a TypeScript file lib/data-retention/purge-customer.ts that implements:
purgeCustomerData(customerId: string, reason: string)— the main purge function- Any helper interfaces or stub service clients needed
Also produce a short DESIGN.md explaining:
- How partial failures are handled (what state is recorded)
- How the legal hold check works
- What the 30-day deadline tracking mechanism looks like (data model or pseudocode is fine)
{
"context": "Tests whether the agent correctly anonymizes order PII while preserving financial data and tax-jurisdiction fields, uses a database transaction for atomicity, stamps a pii_anonymized_at field to prevent re-processing, and uses the correct email anonymization format.",
"type": "weighted_checklist",
"checklist": [
{
"name": "Email anonymization format",
"max_score": 12,
"description": "Anonymized email is set to 'anon_' + order.id + '@deleted.invalid' (exact format)"
},
{
"name": "Customer name cleared",
"max_score": 8,
"description": "customer_name (or customerName) is set to 'Anonymous Customer' (exact string)"
},
{
"name": "Shipping street nulled",
"max_score": 8,
"description": "shipping_street (or shippingStreet/shippingAddress) is set to null, not an empty string or placeholder"
},
{
"name": "City and country preserved",
"max_score": 10,
"description": "shipping_city and shipping_country are NOT overwritten — they retain the original values (code does not assign null/anonymous to these fields)"
},
{
"name": "Financial data untouched",
"max_score": 10,
"description": "Code does NOT overwrite total_amount, tax_amount, payment_method_brand, or payment_method_last4 (these fields are absent from the update payload or explicitly commented as preserved)"
},
{
"name": "Transaction used",
"max_score": 10,
"description": "Anonymization updates are wrapped in a database transaction (db.transaction or trx equivalent)"
},
{
"name": "pii_anonymized_at stamp",
"max_score": 10,
"description": "Each updated record has pii_anonymized_at set to the current date/time"
},
{
"name": "Filter already-anonymized",
"max_score": 12,
"description": "Query filters out records where pii_anonymized_at is NOT NULL (i.e. skips already-anonymized records)"
},
{
"name": "Batch size limit",
"max_score": 10,
"description": "Query uses a LIMIT (e.g. 500) to process records in bounded batches rather than fetching all rows at once"
},
{
"name": "Billing fields cleared",
"max_score": 10,
"description": "billing_name (or billingName) is set to 'Anonymous' AND billing_street (or billingStreet) is set to null"
}
]
}
Order Data Cleanup for Tax Compliance
Problem/Feature Description
A European e-commerce company is preparing for a GDPR compliance review. Their legal team has confirmed that they must retain all order financial records for 7 years to satisfy EU VAT and tax audit requirements — but they are not permitted to hold customer personal information beyond what is strictly necessary. Orders older than 7 years that still contain identifiable customer data need to have that personal information removed, while the underlying financial record must remain intact and accurate.
The engineering team has been asked to write a TypeScript function that processes these old orders. The challenge is that the financial data (amounts, payment method summary, tax figures) is critical for audits and must survive unchanged, while name and address fields should be cleared. The city and country must be preserved for tax jurisdiction purposes. The job may run monthly and must be safe to re-run — it should never double-process a record.
Output Specification
Produce a TypeScript file jobs/anonymize-old-orders.ts that:
- Implements an
anonymizeOldOrders(cutoffDays: number)function - Includes stub types/interfaces for
dband the order model as needed - Has a brief inline comment explaining why city/country are preserved
The output does not need to compile against a real database driver. Focus on the logic: what fields get cleared, how atomicity is ensured, what prevents re-processing.
{
"context": "Tests whether the agent correctly defines the retention schedule with legally-mandated periods and actions for all data categories, implements a paginated/batched purge approach to avoid table locks, schedules jobs at the correct time, and produces an append-only audit log for every retention action.",
"type": "weighted_checklist",
"checklist": [
{
"name": "Orders retention period",
"max_score": 6,
"description": "Retention schedule sets orders retentionDays to 365*7 (2555) or equivalent 7-year value"
},
{
"name": "Orders action anonymize",
"max_score": 6,
"description": "Retention schedule sets orders action to 'anonymize' (not 'delete' or 'archive')"
},
{
"name": "Invoices action archive",
"max_score": 6,
"description": "Retention schedule sets invoices action to 'archive' (not 'delete')"
},
{
"name": "Sessions 90 days",
"max_score": 5,
"description": "Retention schedule sets sessions retentionDays to 90"
},
{
"name": "cartData 30 days",
"max_score": 5,
"description": "Retention schedule sets cartData retentionDays to 30"
},
{
"name": "analyticsEvents 395 days",
"max_score": 5,
"description": "Retention schedule sets analyticsEvents retentionDays to 395 (13 months)"
},
{
"name": "analyticsEvents aggregate_then_delete",
"max_score": 6,
"description": "Retention schedule sets analyticsEvents action to 'aggregate_then_delete' (not plain 'delete')"
},
{
"name": "Cron schedule 2 AM UTC",
"max_score": 8,
"description": "Job cron expression is '0 2 * * *' (nightly at 2 AM UTC)"
},
{
"name": "Batch pagination used",
"max_score": 10,
"description": "Purge functions use a pagination loop (cursor-based or offset) with a row LIMIT rather than a single DELETE/UPDATE query on all rows"
},
{
"name": "Sleep between batches",
"max_score": 8,
"description": "Purge loop includes a delay/yield (e.g. setTimeout or sleep) between batch iterations"
},
{
"name": "Audit log entry per job",
"max_score": 10,
"description": "Each purge/retention job records an audit log entry (insert into retentionAuditLog or equivalent) after running"
},
{
"name": "Audit log fields",
"max_score": 8,
"description": "Audit log entry includes at least: job name, data category or action type, record count, and execution timestamp"
},
{
"name": "Audit log append-only comment",
"max_score": 7,
"description": "Code or README explicitly notes that the audit log table is append-only and must not be deleted from"
},
{
"name": "Error alerting per job",
"max_score": 10,
"description": "Job runner catches errors per individual job and triggers an alert (alertOpsTeam or equivalent) rather than letting the whole runner crash silently"
}
]
}
Implement Data Retention for an E-Commerce Backend
Problem/Feature Description
A fast-growing online marketplace has been accumulating data since launch without any formal data cleanup process. The engineering team has been asked by legal and compliance to implement a proper data retention system before an upcoming SOC 2 audit. The platform stores customer sessions, abandoned shopping carts, browsing history, fraud detection logs, analytics events, and customer account records in a PostgreSQL database.
The legal team has reviewed applicable regulations (US tax law, EU VAT, GDPR) and signed off on a retention policy document. Engineering needs to translate this into running code: a TypeScript module that defines the retention schedule and a nightly background job that enforces it. The compliance team specifically needs evidence that the jobs are actually running and purging data — they want an audit trail they can show to auditors.
The system must be safe for production: it cannot lock database tables during business hours, and it must handle large tables gracefully without timing out.
Output Specification
Produce a TypeScript implementation with the following files:
lib/data-retention/schedule.ts— defines the retention schedule as a typed constantjobs/data-retention.ts— the nightly retention job runner (cron scheduling, all purge functions, execution tracking)README.md— a brief explanation of the cron schedule chosen and the approach used to avoid database table locks
The output does not need to compile or connect to a real database — stub the db and CronJob imports as needed. Focus on the logic, structure, and configuration values.
{
"name": "finsi/data-retention-policies",
"version": "0.1.0",
"summary": "Order/customer data lifecycle management and automated purging",
"skills": {
"data-retention-policies": {
"path": "SKILL.md"
}
}
}