Admissions open for our live online programs · Starts 5 December 2026 · Live online, learn from anywhere

Forward Deployed Engineering

Data Governance and Privacy for AI Systems: A Practical Guide for Engineers

How to govern data and protect privacy in RAG and AI agent systems: classification, PII masking, permission-aware retrieval, audit logs, DPDP, GDPR and EU AI Act basics.

Short answer: Data governance for an AI system means knowing which data the system can see, who is allowed to see it through the system, how personal data is minimised or masked, and being able to prove all of that later. In practice that is six controls: classify sources before indexing, mask personal data before it is embedded or logged, filter retrieval by the user's permissions before ranking, give agents least-privilege tools, keep an audit trail, and support retention and erasure. Laws such as India's DPDP Act, the GDPR and the EU AI Act set the rules; engineering is how you meet them.

This guide is for engineers who build retrieval-augmented generation (RAG) systems and AI agents on real company data: forward deployed engineers, AI engineers and data engineers. It is not legal advice. For any real deployment, work with the customer's privacy or legal team; your job is to make their requirements true in code.

Why AI systems need their own data governance

Traditional data governance was built for warehouses and dashboards. A report shows the same columns to everyone who opens it, and access is granted per table. AI systems break that model in three ways.

They mix sources. A single RAG answer can pull a paragraph from an HR policy, a row from a CRM and an email thread, then blend them into one fluent reply. If any of those chunks should not have reached the person asking, the answer leaks it, and it does so in natural language that no DLP rule was written for.

They copy data into new places. Text gets chunked, embedded and stored in a vector database, cached, written to prompt logs, and sometimes sent to a third-party model API. Each copy is a new place where personal data lives and must be secured, kept only as long as needed and deleted on request.

They act. An agent with tools does not just read data; it can send it somewhere. An agent that can both read a customer table and send email can exfiltrate that table if a prompt injection tells it to.

The OWASP Top 10 for LLM Applications (2025) names this risk directly. Its entry on Sensitive Information Disclosure says sensitive information "includes personal identifiable information (PII), financial details, health records, confidential business data, security credentials, and legal documents" (OWASP LLM02:2025). Its entry on vector and embedding weaknesses warns that "inadequate or misaligned access controls can lead to unauthorized access to embeddings containing sensitive information" (OWASP LLM08:2025).

The rules you will meet (in plain English)

You do not need to be a lawyer, but you should recognise the frameworks a customer's security review will mention. Here are the ones that come up most often for teams in India and teams serving global clients.

The rules you will meet (in plain English)
FrameworkWhere it appliesWhat it means for an AI engineer
India's Digital Personal Data Protection (DPDP) Act, 2023 and DPDP Rules, 2025Digital personal data processed in India, and processing outside India connected to offering goods or services to people in India (DPDP Act, section 3)Collect for a stated purpose, keep only what you need, secure it, support access, correction and erasure requests, and report breaches
EU General Data Protection Regulation (GDPR)Personal data of people in the EUPurpose limitation, data minimisation and data protection by design, for example pseudonymisation
EU AI Act, Article 10Training, validation and testing data for high-risk AI systemsDocumented data governance and management practices, and data that is relevant, representative and as free of errors as possible
NIST AI Risk Management FrameworkVoluntary, widely used as a referenceA shared vocabulary for mapping, measuring and managing AI risks
OWASP Top 10 for LLM Applications (2025)Industry security guidanceConcrete failure modes and mitigations: sensitive information disclosure, vector and embedding weaknesses, excessive agency

A few specifics worth knowing:

  • DPDP in India. The government's release on the DPDP Rules says the Act "is guided by seven core principles including consent and transparency, purpose limitation, data minimisation, accuracy, storage limitation, security safeguards, and accountability", and that the Rules "provide an 18-month phased compliance timeline" (PIB, 14 November 2025). Consent Manager registration came into effect on 13 November 2026, and the government says the main obligations of Data Fiduciaries and the rights of Data Principals "are scheduled to come into effect on 13 May 2027" (PIB, 14 November 2026). If you are building an AI system in India today, design for those obligations now rather than retrofitting them in 2027.
  • GDPR. Article 5 lists the principles, including purpose limitation and data minimisation: personal data should be "adequate, relevant and limited to what is necessary" for the purpose (GDPR Art. 5). Article 25 asks controllers to build in measures "such as pseudonymisation" by design (GDPR Art. 25).
  • EU AI Act. Article 10 requires that training, validation and testing data for high-risk AI systems be subject to data governance and management practices appropriate for the system's intended purpose, and that the data be relevant, sufficiently representative and, to the best extent possible, free of errors and complete (EU AI Act, Article 10). Most RAG chatbots are not high-risk systems, but customers in regulated sectors increasingly ask for the same discipline anyway.
  • NIST AI RMF. NIST says the framework "is intended for voluntary use" to help teams build trustworthiness into AI design, development, use and evaluation (NIST AI RMF). Enterprise risk teams often use its language.

The practical takeaway: whichever law applies, the engineering asks are nearly identical. Know your data, use only what the purpose needs, control access, protect personal data, keep records, and be able to delete.

Where data leaks in a RAG or agent system

Before choosing controls, map where data flows. In a typical enterprise RAG or agent system, personal or confidential data can leak at eight points:

  1. Ingestion. A crawler or connector pulls in documents nobody meant to include, such as an HR folder shared too widely.
  2. Chunking and embedding. Raw personal data ends up inside chunks and embeddings. Embeddings are not anonymous; they are derived from the text, and the original chunk is usually stored next to them.
  3. The vector store. One shared index for all users means any user's query can retrieve any chunk.
  4. Retrieval. Results are ranked first and filtered later (or not filtered at all), so restricted chunks slip into the context window.
  5. The prompt sent to the model. Context goes to an external model API, possibly outside the country, under terms someone needs to have checked.
  6. The answer. The model repeats a restricted detail to someone who should not see it.
  7. Logs and traces. Prompts, retrieved chunks and answers are logged in plain text for debugging and kept forever.
  8. Agent tools. An agent with broad tools (send email, query any table, write files) can move data out of the system.

Each control in the next section closes one or more of these points.

Six controls that make an AI system governable

1. Inventory and classify sources before you index anything

Start with a simple register for every source the system will read: owner, purpose, classification (public, internal, confidential, restricted), whether it contains personal data, whose personal data, the legal basis or consent, and the retention period. Store the classification and the allowed groups as metadata on every chunk, because everything downstream depends on it.

This is ordinary data engineering discipline, the same lineage and cataloguing work covered in stage 7 of our data engineering roadmap. The difference is that in an AI system it has to travel with each chunk, not just sit in a catalogue.

2. Minimise and mask personal data before embedding

Ask first whether the system needs the personal data at all. A policy assistant does not need employees' phone numbers. If it is not needed, mask or remove it before chunking and embedding, and before anything is logged. If it is needed for some users, keep the detail in the source system and let the agent fetch it with a permission-checked tool at question time rather than copying it into the index.

Pattern-based masking catches structured identifiers such as email addresses, phone numbers and ID numbers. Names, addresses and free-text health details need named-entity detection. Open-source tools such as Presidio provide "identification and anonymization modules for private entities in text and images", but its own documentation warns that "there is no guarantee that Presidio will find all sensitive information" (Presidio). Treat masking as one layer, not as the only protection.

3. Filter retrieval by permission before ranking

This is the control most often missing from demos. OWASP's mitigation for vector and embedding weaknesses is to "implement fine-grained access controls and permission-aware vector and embedding stores" (OWASP LLM08:2025). In practice:

  • Copy the source system's permissions onto chunks as metadata (groups, tenant, region), and keep them in sync when permissions change.
  • Apply the user's permissions as a filter inside the retrieval query, so restricted chunks are never candidates. Do not retrieve the top 10 and then drop the restricted ones; that leaks information through ranking and often leaves too few results.
  • For multi-tenant systems, partition indexes by tenant rather than relying on one filter.
  • Identify the user from your authentication system, never from something the model or the user's message says.

4. Give agents least-privilege tools and approval steps

Agents turn a privacy problem into an action problem. Give each agent only the tools it needs, scope each tool to read-only where possible, run tools under a service identity with narrow rights, and put a human approval step in front of anything that sends data out or changes records. Our guide to human-in-the-loop AI agents shows how to make an agent pause for approval in LangGraph, n8n and other platforms.

5. Log for accountability, not for curiosity

Customers and regulators will ask: who asked what, which data was used, and what the system did. Log the user, the time, the documents or records retrieved, the tools called and the decision taken. Avoid logging raw prompts and answers by default; if you must keep them for evaluation, mask them, restrict access and set a retention period. Tracing tools are useful, but check what they store and where.

6. Support retention, correction and erasure

Every copy of personal data needs a deletion path: the source, the chunks, the embeddings, caches, evaluation datasets and logs. Store a link from each chunk back to its source document and, where relevant, to the person the data is about, so an erasure request can be carried out across the whole pipeline. Re-index on a schedule so corrected or deleted source data does not survive in the index.

A small working example in Python

The script below shows controls 2, 3, 5 and 6 together in about 80 lines of standard-library Python. It masks structured personal data before indexing, filters retrieval by the user's groups before ranking, writes an audit record without storing the raw question, and erases everything linked to one person. Keyword overlap stands in for vector search so the code runs anywhere; in a real system you would apply the same permission filter inside your vector database query.

import json, re, hashlib
from datetime import datetime, timezone

# 1. Mask personal data BEFORE anything is chunked, embedded or logged.
PII_PATTERNS = {
    "EMAIL": r"[\w.+-]+@[\w-]+\.[\w.]+",
    "PHONE_IN": r"(?:\+91[\s-]?)?[6-9]\d{9}\b",
    "PAN": r"\b[A-Z]{5}\d{4}[A-Z]\b",
    "AADHAAR_LIKE": r"\b\d{4}\s?\d{4}\s?\d{4}\b",
}

def mask_pii(text):
    found = []
    for label, pattern in PII_PATTERNS.items():
        for match in re.findall(pattern, text):
            found.append(label)
        text = re.sub(pattern, f"<{label}>", text)
    return text, found

# 2. Every document carries governance metadata: owner, classification,
#    who may read it, and whose personal data it contains (for erasure).
RAW_DOCS = [
    {"id": "hr-01", "text": "Leave policy: employees get 24 days of paid leave per year.",
     "classification": "internal", "allowed_groups": ["all_staff"], "data_principal": None},
    {"id": "hr-02", "text": "Priya Sharma (priya.s@example.com, 9876543210) is on medical leave until 15 Dec.",
     "classification": "confidential", "allowed_groups": ["hr"], "data_principal": "priya.s@example.com"},
    {"id": "fin-01", "text": "New vendors need CFO approval before the first payment. Vendor PAN ABCDE1234F is on hold.",
     "classification": "confidential", "allowed_groups": ["finance"], "data_principal": None},
]

INDEX = []
for doc in RAW_DOCS:
    clean, found = mask_pii(doc["text"])
    INDEX.append({**doc, "text": clean, "pii_masked": found})

# 3. Retrieval filters by permission FIRST, then ranks. Never rank first and filter later.
def tokens(s):
    return set(re.findall(r"[a-z]+", s.lower()))

AUDIT_LOG = []

def retrieve(question, user, k=2):
    visible = [d for d in INDEX if set(d["allowed_groups"]) & set(user["groups"])]
    scored = sorted(visible, key=lambda d: len(tokens(question) & tokens(d["text"])), reverse=True)
    hits = [d for d in scored[:k] if tokens(question) & tokens(d["text"])]
    # 4. Audit: who asked, a hash of the question (not the raw text), which docs were used.
    AUDIT_LOG.append({
        "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "user": user["id"],
        "question_sha256": hashlib.sha256(question.encode()).hexdigest()[:16],
        "doc_ids": [d["id"] for d in hits],
    })
    return hits

# 5. Erasure: remove everything linked to one person when they withdraw consent.
def erase_data_principal(principal):
    before = len(INDEX)
    INDEX[:] = [d for d in INDEX if d["data_principal"] != principal]
    return before - len(INDEX)

if __name__ == "__main__":
    employee = {"id": "u-101", "groups": ["all_staff"]}
    hr_user = {"id": "u-007", "groups": ["all_staff", "hr"]}
    q = "Who is on medical leave?"
    print("employee sees:", [d["id"] for d in retrieve(q, employee)])
    print("hr sees:      ", [(d["id"], d["text"]) for d in retrieve(q, hr_user)])
    print("fin-01 stored as:", INDEX[2]["text"])
    print("erased docs:", erase_data_principal("priya.s@example.com"))
    print("hr sees after erasure:", [d["id"] for d in retrieve(q, hr_user)])
    print(json.dumps(AUDIT_LOG[0]))

Output (Python 3.13; the timestamp will differ):

employee sees: ['hr-01']
hr sees:       [('hr-02', 'Priya Sharma (<EMAIL>, <PHONE_IN>) is on medical leave until 15 Dec.'), ('hr-01', 'Leave policy: employees get 24 days of paid leave per year.')]
fin-01 stored as: New vendors need CFO approval before the first payment. Vendor PAN <PAN> is on hold.
erased docs: 1
hr sees after erasure: ['hr-01']
{"ts": "2026-12-01T08:48:58+00:00", "user": "u-101", "question_sha256": "61fe3f424a0605b6", "doc_ids": ["hr-01"]}

What the output teaches:

  • The ordinary employee never sees the confidential HR note, because it was never a retrieval candidate for their groups. They get the general leave policy instead.
  • The email and phone number are masked even for HR, because the index never held them. If HR needs the contact details, a permission-checked tool can fetch them from the HR system.
  • The name "Priya Sharma" was not masked. Regular expressions cannot reliably find names; that needs entity detection, plus a decision on whether names belong in the index at all. This is exactly the gap Presidio's warning describes.
  • After erasure, the person's record is gone from the index. In production, the same request must also reach the embeddings, caches, evaluation sets and logs.

A governance checklist for your next AI project

Use this as a discovery and design checklist with the customer's data owners and security team:

  1. List every data source, its owner, purpose and classification.
  2. Mark which sources contain personal data, whose, and on what basis it is processed.
  3. Decide what the AI system actually needs, and leave out the rest.
  4. Mask or remove personal data before chunking, embedding and logging.
  5. Carry permissions as chunk metadata and filter inside the retrieval query.
  6. Partition indexes by tenant or region where required.
  7. Check where the model API processes data and what its terms say about retention and training.
  8. Give agents read-only, narrowly scoped tools; add approval steps for writes and outbound messages.
  9. Log user, data used, tools called and outcome; set retention for every log.
  10. Build an erasure path across source, index, cache, evaluation data and logs.
  11. Test it: red-team prompts that try to extract restricted data, and evaluation cases that check access rules.
  12. Write it down: a short governance pack with data flows, controls and owners, which the customer's reviewers can sign off.

Point 11 matters more than it looks. Add access-control tests to your evaluation set, for example "ask, as a user without HR access, who is on medical leave", and fail the build if restricted content appears. Our RAG pipeline guide covers building that evaluation set.

Common mistakes

  • Treating the vector database as anonymous. Chunks sit next to their embeddings, and both come from your source text.
  • Filtering after ranking. It leaks information and returns fewer useful results. Filter in the query.
  • Trusting the prompt for access control. "Only answer HR questions for HR staff" in a system prompt is not a control; prompt injection can override it.
  • Logging everything for debugging. Debug logs become the largest store of personal data in the system.
  • Forgetting copies. Erasure that deletes the source but not the index, cache or evaluation data is not erasure.
  • Leaving governance to the end. A security review that finds these issues late can hold up a go-live. Put the checklist in your discovery phase.

Who does this work, and how to learn it

In enterprise AI projects this work usually lands on the engineer who sits closest to the customer. A forward deployed engineer has to get a system through the customer's security review, which means designing these controls, explaining them to a privacy team and producing the documentation. Data engineers own much of it too: catalogues, lineage, retention and deletion jobs. If you want to compare how FDE courses cover governance, see our FDE courses compared guide.

At Datamarcos, the Forward Deployed AI Engineer program includes a full week on AI security (prompt injection, the OWASP LLM Top 10, PII masking and guardrails) and a full week on governance and compliance essentials (DPDP, GDPR, HIPAA and the EU AI Act), and learners produce a governance pack and risk register in their client-style engagements. The Generative AI & Agentic AI Engineer program covers the same essentials in its production and security month, and the Advance Data Engineering with Applied GenAI & Agentic AI program builds the data foundation underneath. Placement support, not a job guarantee.

For teams, we run corporate training on secure, governed AI systems; Datamarcos has trained teams at 200+ organizations. More free guides are on the guides hub.

FAQ

What is data governance for AI systems?

Data governance for AI systems is the set of rules and controls that decide which data an AI system may use, who can see that data through it, how personal data is minimised or masked, how long copies are kept and how decisions are recorded. It covers sources, indexes, prompts, logs and agent tools, not just the training data.

Which measures are essential for maintaining data privacy in AI systems?

Six measures matter most: classify sources before indexing, minimise and mask personal data before embedding or logging, filter retrieval by the user's permissions inside the query, give agents least-privilege tools with approval steps, keep an audit trail of data used and actions taken, and support retention and erasure across every copy.

How do I stop a RAG chatbot from leaking confidential documents?

Store each chunk's permissions as metadata, take the user's identity from your login system, and apply those permissions as a filter inside the vector search so restricted chunks are never retrieved. Partition indexes by tenant where needed, never rely on the system prompt for access control, and add access-control test cases to your evaluation set.

Does India's DPDP Act apply to AI systems?

The DPDP Act applies to digital personal data, so it covers AI systems that process such data, including RAG indexes and logs. The DPDP Rules, 2025 phase in over 18 months: Consent Manager rules took effect on 13 November 2026, and the main obligations of Data Fiduciaries are scheduled for 13 May 2027. Take legal advice for specific cases.

Is masking PII enough to make an AI system private?

No. Masking is one layer. Pattern-based masking misses names and free-text details, and entity-detection tools also miss some cases, as Presidio's own documentation warns. You also need data minimisation, permission-aware retrieval, least-privilege agent tools, controlled logging and an erasure path, plus testing that tries to extract restricted data.

Which forward deployed engineer courses include data governance and privacy for AI systems?

In our comparison of FDE programs, all eight with detailed public syllabi name AI security and governance, but "named" says nothing about depth. Ask for the week-by-week plan and whether you build hands-on controls such as RBAC, PII masking and audit trails. Datamarcos's FDE program has a full governance and compliance week.

Do data engineers need to learn AI governance?

Yes, increasingly. Data engineers already own catalogues, lineage, quality, retention and deletion jobs, and AI systems depend on all of them. Adding classification metadata to chunks, permission-aware indexes and erasure across vector stores is a natural extension of the role, and it makes data engineers far more useful on GenAI projects.

Related program

Forward Deployed AI Engineer program

22 weeks live online, 170+ live hours and four client-style engagements, from customer discovery to production handover. Built for working engineers.

See the 22-week FDE syllabus

Sources

Accessed 1 December 2026.

Contact Us