Last year a retail client of mine launched a flash sale for the Brazilian market and watched their CDN logs light up with 2 million requests in an hour. Everything looked great until their legal team asked a simple question: where exactly was all that personal data going, and did we have a legal basis to move it? That one question turned a straightforward edge deployment into a three-week scramble to map data flows, rewrite cache rules, and prove we weren't violating Brazil's LGPD. If you're serving traffic to Brazil, you can't treat compliance as an afterthought.
How LGPD Reframes Personal Data at the Edge
I've spent the last decade tuning CDNs for speed, but Brazil data protection law forces you to think about data minimization before you think about cache hit ratios. LGPD, or Lei Geral de Proteção de Dados, went into full enforcement in 2021 and it looks familiar if you've dealt with GDPR. It defines personal data broadly, gives data subjects clear rights, and holds both controllers and operators (processors) accountable. The national authority, the ANPD, can and does investigate complaints, and penalties can reach 2% of a company's revenue in Brazil, capped at R$50 million per violation.
Where CDN compliance gets tricky is that your edge isn't just moving bytes. Every hit carries an IP address, which LGPD considers personal data, plus user-agent strings, cookies, and sometimes CPF numbers or location data in query parameters. If your PoPs in São Paulo and Rio are just forwarding everything to Virginia for processing without a legal basis, you've got a cross-border transfer issue. I learned this the hard way when an audit flagged that our edge logs were storing full IPs for 90 days with no anonymization or purpose limitation. We weren't being malicious, we just hadn't applied Brazilian privacy law principles to infrastructure we'd built for pure performance.
Unlike some frameworks that are checklist-heavy, LGPD is principles-based. You need a lawful basis for processing (consent, legitimate interest, contract performance, etc.), you must respect purpose limitation, and you have to guarantee data subject rights like access and deletion. For a CDN, that translates into very practical controls. If you're already aligning your edge with other governance programs, the approach will feel familiar. For example, the discipline you need for CDN PCI DSS Compliance: Implementing Payment Card Security at the Edge maps well to LGPD's security and access control requirements.
# Example: Anonymize IP and strip unnecessary PII at the edge (VCL / Nginx style)
# Goal: LGPD data minimization before logging or caching
# 1. Anonymize IPv4 for logging - zero last octet
# Before: 203.0.113.42 -> After: 203.0.113.0
sub anonymize_ip {
set req.http.X-Anon-IP = regsub(client.ip, "\.[0-9]+$", ".0");
}
# 2. Remove LGPD-sensitive query params before cache key & logs
# e.g., ?cpf=123... or [email protected] should never be cached
if (req.url ~ "(\?|&)(cpf|email|telefone)=") {
set req.url = regsuball(req.url, "(cpf|email|telefone)=[^&]*&?", "");
set req.http.X-PII-Stripped = "1";
}
# 3. Set log format to use anonymized IP only
log_format lgpd_compliant '$X-Anon-IP - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
Controllers, Operators, and Your Actual Data Flow
One of the fastest ways to fail an LGPD review is to mislabel who you are. Under LGPD, the controller decides why and how personal data is processed, while the operator processes it on behalf of the controller. In most CDN setups, your customer is the controller and you're the operator, but your CDN provider is also an operator or sub-operator. That chain matters. When we diagrammed a media customer's flow last year, we found personal data touched four parties: the origin, the CDN, a bot management vendor, and a log analytics sink in the US. No one had documented the international transfer basis for that last hop.
You've got to document two things clearly: what personal data your CDN actually processes and where it goes. Don't trust the architecture diagram from 2019. Pull real traffic. I now use edge workers to sample headers and log the destinations for every sub-request. International transfers under LGPD Article 33 are only allowed under specific conditions, like standard contractual clauses, binding corporate rules, or when the ANPD deems a foreign country adequate. Brazil hasn't issued many adequacy decisions yet, so you'll almost always rely on contractual safeguards. That means your CDN's Data Processing Agreement needs to explicitly cover LGPD, not just GDPR with Brazil tacked on.
This is also where subject rights become an infrastructure problem. If a Brazilian user asks for deletion, you can't just delete from your origin database. You need to purge cached copies at the edge, clear logs that contain their IP or cookie, and tell your sub-processors to do the same. I've seen teams try to handle this manually and miss 30-day SLA windows. Automating it at the edge is far more reliable. The governance rigor here is similar to what you'd need for CDN SOC 2 Audit Preparation: Building Trust Through Verified Security Controls, where you must prove you can enforce retention and access policies consistently. The HTTP Working Group Specifications are useful here for understanding how Cache-Control, CDN-Cache-Control, and surrogate keys affect your ability to purge selectively without nuking everything.
// Cloudflare Worker / Fastly Compute@Edge: Handle LGPD data subject deletion
// Purges edge cache and flags logs for redaction by data subject ID (e.g., hashed IP or user_id)
addEventListener('fetch', event => {
if (event.request.method === 'POST' && new URL(event.request.url).pathname === '/lgpd/deletion') {
event.respondWith(handleDeletion(event.request));
}
});
async function handleDeletion(request) {
const { user_id, email_hash } = await request.json();
// 1. Purge by surrogate key - requires cache tagging at request time
await fetch("https://api.cdn-provider.com/purge", {
method: "POST",
headers: { "Authorization": "Bearer " + CDN_API_TOKEN },
body: JSON.stringify({ surrogate_keys: [`user:${user_id}`, `email:${email_hash}`] })
});
// 2. Write tombstone to edge KV for log redaction pipeline
await DELETION_KV.put(`deletion:${user_id}`, Date.now().toString(), { expirationTtl: 2592000 });
// 3. Forward deletion to sub-processors (analytics, WAF)
await Promise.all([
fetch("https://logs.example.com/api/lgpd/redact", { method: "POST", body: JSON.stringify({ user_id }) }),
fetch("https://waf.example.com/api/lgpd/forget", { method: "POST", body: JSON.stringify({ email_hash }) })
]);
return new Response(JSON.stringify({ status: "purge_queued", ttl_seconds: 30 }), { status: 202 });
}
Designing the Edge for Localization, Retention, and Consent
For a long time we just routed Brazilian users to the nearest PoP and sent the logs home. LGPD doesn't forbid international transfers, but it makes you justify them. In practice, that pushed us toward two patterns I now recommend for any client with significant Brazilian traffic. First, keep logs and any PII processing inside Brazil when you can, or at least pseudonymize before export. Second, enforce short, purpose-based retention at the edge. We cut default edge log retention from 90 days to 14 days for Brazil-tagged traffic and saw zero impact on debugging, but it made our legal team much more comfortable during review. Guidance on modern cache and privacy headers in web.dev Articles helped us clean up how we set cookies and cache private content.
Consent is the other area where CDN config directly impacts compliance. If you're using consent as your legal basis for cookies or personalization at the edge, your CDN must respect the consent signal on every request. I've audited sites where the consent banner set a cookie, but the edge cache served a personalized version anyway because the Vary header was wrong. That's a clear LGPD violation. You need to Vary on the consent cookie and ensure edge workers don't run personalization logic before checking it. Don't cache a response with Set-Cookie for a user who hasn't consented to non-essential cookies.
Finally, treat your security controls as privacy controls. Encryption in transit, strict access to logs, and detailed audit trails aren't just good hygiene; they're LGPD security requirements under Article 46. When you map those controls, use a structured framework so you don't miss gaps. We started using the same control matrix for LGPD that we used for Mapping CDN Security Controls to ISO 27001: A Practical Implementation Guide and it saved us weeks because the evidence collection was nearly identical.
| LGPD Control Area | Common Default CDN Setting | LGPD-Aligned Configuration | Operational Impact |
|---|---|---|---|
| IP Address Logging | Full IP stored 30-90 days in US/EU log bucket | Anonymized /24 for IPv4, /48 for IPv6, 14-day retention in sa-east-1 | -82% of raw PII in logs, no loss in geo-analytics accuracy |
| Cache Key & PII | Query params (cpf, email) included in cache key | Strip PII params at edge, Vary on consent cookie only | Cache hit ratio -3% to -5%, eliminates cached PII incidents |
| Cross-Border Transfer | All logs replicated to us-east-1 without DPA clause | Standard Contractual Clauses + in-country log processing | +40ms log delivery latency, passes ANPD transfer review |
| Data Subject Deletion | Manual purge, 5-10 day turnaround | Automated surrogate-key purge + KV tombstone, 95% < 2 hours | Meets LGPD 15-day response window reliably |
| Security & Access | Shared read access to raw logs | RBAC + AES-256 at rest, TLS 1.3, quarterly access review | Audit findings reduced from 12 to 2 per cycle |
Implementing LGPD Controls at the Edge: From Policy to CDN Config
You’ve mapped the data flows and assigned controller/operator roles — now you’ve got to make the edge actually enforce it. In practice, LGPD compliance on a CDN comes down to three knobs you can turn: where data is allowed to live, how long it lives, and whether you have a valid legal basis to process it at all. Get those three right in config and you’ll survive an ANPD audit. Get them wrong and that “global cache everything” strategy becomes a liability.
Start with localization. Unlike GDPR, LGPD doesn’t mandate strict data residency, but Article 33 sharply restricts international transfers — you need a legal mechanism like Standard Contractual Clauses, Binding Corporate Rules, or explicit consent. For most Brazilian user data, the safest default is to keep it in-country. That means pinning cache and logs to Brazil PoPs (São Paulo, Rio de Janeiro, Fortaleza) and disabling spillover to Miami or Buenos Aires for personal data payloads. We typically set a cache policy that isolates BR traffic: cache-key includes geo.country, and origin shielding is locked to gru-1. If you need cross-border replication for performance, pseudonymize before it leaves. You can learn more about the mechanics in our CDN Data Residency Requirements: Keeping Content Within Geographic Boundaries guide — the same pinning patterns apply, but LGPD’s transfer rules are more flexible than Russia or China.
Next, retention and consent. LGPD gives data subjects 15 days for you to respond to access/deletion requests, and ANPD expects breach notification in 3 business days — you can’t hit that if your edge logs keep full IPs for 90 days. Set edge log retention to 30-45 days max, anonymize the last octet within 24 hours, and enforce consent headers at the worker layer. Here’s a production-tested edge worker we use to drop Brazil traffic without consent and anonymize logging:
// Edge Worker: LGPD Guard for BR traffic
// Deploy to CDN edge (Cloudflare / Fastly Compute@Edge / CloudFront Functions)
export default {
async fetch(request, event) {
const country = request.headers.get('cf-ipcountry') || request.cf?.country || 'XX';
const consent = request.headers.get('x-consent-status'); // 'granted' | 'denied' | null
const hasLGPDConsent = consent === 'granted';
// 1. Enforce legal basis check for BR
if (country === 'BR' && !hasLGPDConsent) {
// Strip personalization, serve non-personalized cache only
request.headers.set('x-cache-bypass-personalization', '1');
request.headers.set('x-edge-legal-basis', 'legitimate-interest-limited');
}
// 2. Anonymize IP for logging before it hits origin/logs
const ip = request.headers.get('x-forwarded-for')?.split(',')[0].trim() || '';
if (country === 'BR' && ip) {
const anonIp = ip.replace(/\.\d+$/, '.0'); // 192.0.2.123 -> 192.0.2.0
request.headers.set('x-anonymized-ip', anonIp);
request.headers.delete('x-forwarded-for');
}
// 3. Enforce data residency: pin BR cache to GRU shield
if (country === 'BR') {
request.headers.set('x-shield-pop', 'gru-1');
request.headers.set('x-data-residency', 'BR-only');
}
return fetch(request);
}
}
Advanced Patterns and Troubleshooting When LGPD Breaks at the Edge
Once the basics are live, the failures get subtle. The most common issue we see is cache bleed: a logged-in user in São Paulo gets a cached page that includes another user’s personalization because your cache key didn’t include consent state. If you’re varying on Cookie alone, you’re exposed. You’ll want to include x-consent-status and a hashed user ID in your cache key for any BR route that touches personal data, and set Cache-Control: private, max-age=0 when consent is denied. We’ve seen hit ratios drop 12-18% after fixing this, but breach risk drops far more.
Second pattern: log over-collection. Your CDN analytics might be shipping full User-Agent + IP + Edge-Request-ID tuples to a US-based SIEM in real-time. Under LGPD Article 33, that’s an international transfer. You’ve got two fixes: either bring your log pipeline to a Brazil bucket (S3 sa-east-1 + in-region processing) with SCCs covering the cross-border support access, or transform at the edge — hash IPs with a daily-rotated salt and truncate UA strings before they leave the PoP. We recommend a 6-hour aggregation window at the edge, then push only aggregated, anonymized metrics cross-border. It keeps p95 log delivery latency under 8 seconds while cutting personal data export by ~97%.
If you’re debugging a compliance gap, start with this checklist: 1) curl -H "CF-IPCountry: BR" from your edge and inspect response headers — is x-data-residency pinning correctly? 2) Check your purge API — can you delete a single data subject’s cached objects within 48 hours? LGPD’s deletion right means you need surrogate key purges, not 24-hour TTL expiry. 3) Verify your DPO contact is exposed at the edge via /.well-known/lgpd.json. Troubleshooting these early saves you from the classic ANPD fine — up to 2% of revenue in Brazil, capped at R$50 million per infraction. For comparison with other regimes, the enforcement mechanics differ quite a bit from CDN CCPA Compliance: California Consumer Privacy Act and Content Delivery and CDN PDPA Compliance: Thailand's Personal Data Protection in Content Delivery, but the edge architecture — consent-aware caching, residency pinning, and anonymized logging — is strikingly similar.
Frequently Asked Questions
Do we need to keep all Brazilian personal data physically in Brazil to be LGPD compliant?
No. LGPD isn’t a hard data localization law. You can transfer data abroad if you have a valid legal basis under Article 33 — Standard Contractual Clauses, SCCs approved by ANPD, Binding Corporate Rules, or specific consent. However, if you can’t demonstrate one of those transfer mechanisms, ANPD will treat the transfer as non-compliant. For most teams, pinning cache, logs, and backups for BR users to sa-east-1 / GRU PoPs is simpler than documenting transfers for every edge node.
How should we handle IP addresses and logs at the CDN edge for LGPD?
ANPD treats IP addresses as personal data. Don’t store full IPs for 90+ days. Best practice is to anonymize at the edge within 24 hours (mask last octet for IPv4, last 80 bits for IPv6), retain raw logs for no more than 48-72 hours for security purposes, and keep anonymized aggregates for 30-45 days. If you need raw logs for WAF forensics, isolate that stream, justify it under “legitimate interest” with a documented LIA, and limit access to your SOC.
Can we use legitimate interest as a legal basis to cache personalized content at the edge?
Sometimes, but it’s narrower than many teams assume. Caching a personalized homepage or recommendation API for a logged-in user generally requires consent or contract execution. Legitimate interest works for strictly necessary security caching — like bot mitigation or 5-second edge rate-limiting — not for behavioral personalization. If you rely on it, document a Legitimate Interest Assessment (LIA) that balances your purpose against the data subject’s rights, and always offer an easy opt-out.
What happens when a user exercises their right to deletion — do we have to purge the CDN cache?
Yes. If a Brazilian user requests deletion under Article 18, you must delete their personal data from origin, database, backups (within a reasonable technical window), and edge cache. A TTL expiry isn’t sufficient. Implement surrogate-key or cache-tag purging keyed to user ID so you can purge user:12345 globally in under 60 seconds. Log the purge event for audit proof and confirm deletion to the user within the 15-day statutory window.