Database activity monitoring (DAM) is the practice of recording every query sent to a database along with who sent it, what came back and what policy did about it. Most databases don’t keep that record out of the box. PostgreSQL ships with log_statement set to none, and even its mod setting logs every write and not a single SELECT, which is the statement someone copying data out would run.

What is database activity monitoring?

Database activity monitoring is a security control that captures what happens in a database (logins, queries, schema and permission changes, the results returned) and keeps that record outside the database, where the people being watched can’t change it. A DAM tool then searches the record, raises alerts on activity that looks wrong and, in some designs, blocks a query before it runs.

The blocking variant used to go by database activity monitoring and prevention (DAMP), and older sources call the category enterprise database auditing. Whatever the name, a useful record answers four questions about each query: which person, service or agent sent it, what it touched, how much data came back, and whether a policy allowed, changed or stopped it.

The usual DAM use cases each start from a question somebody has to answer. Who read cardholder or patient data last quarter? That’s the compliance one, and PCI DSS, HIPAA and SOX audits all ask a version of it. What did a leaked credential do between the leak and its rotation, and which tables did it touch? Then there are the database admins, who hold the most access and often control the native logs that would record them. Newest on the list: AI agents and BI tools, which send queries on behalf of people who never appear in the database’s own log.

How does database activity monitoring work?

Database activity monitoring works by collecting each statement at one of three points: inside the database engine through its native audit feature, on the database host through an installed agent, or in the connection path through a proxy that clients connect to instead of the database. The collection point decides which identity the record can name, whether the monitor can stop a query, and what it never sees.

Native audit (in the engine)Host agent (on the server)In-path proxy (in the connection path)
ExamplesPostgreSQL log_statement, pgAudit, Aurora Database Activity StreamsA vendor agent on a self-managed serverA protocol-aware proxy that clients authenticate to
Identity on the recordThe database roleThe database role and the local OS sessionWhoever authenticated to the proxy: a person, a service or an agent
Can it block a query?NoSome productsYes, before the query reaches the database
Managed services (RDS, Snowflake)Only what the provider exposesNo host to install onYes
Blind spotWhat the setting excludes, and anything after an admin changes itPeople behind a shared roleConnections that go around it

Native auditing costs nothing to turn on and can see everything the engine executes, admin sessions included. Its weakness is who controls it. In PostgreSQL only superusers, or roles granted the right SET privilege, can change log_statement, and those are exactly the accounts a DAM program most needs to watch. pgAudit adds session and object audit logging on top of the standard log, still under the database role; our Postgres audit logging section compares it with a proxy.

Managed services offer their own stream. Aurora’s Database Activity Streams push activity to an Amazon Kinesis stream encrypted with your KMS key, and database admins have no access to it, which fixes the control problem. AWS is candid about the trade-off underneath. Asynchronous mode “favors database performance over the accuracy of the activity stream” and can lose records, flagged afterwards by an RDS event, while synchronous mode, available only on Aurora PostgreSQL, holds the session until the event is durable. Every collection point makes some version of that choice.

A host agent sees what never crosses the network, such as an admin who logs into the server and runs psql locally. It has nowhere to run on RDS, Cloud SQL or Snowflake, and it has to keep pace with every database version and OS patch on the fleet.

An in-path proxy terminates the client’s connection, authenticates the person or workload, reads the query before the database does and reads the results on the way back, which makes it the only position from which a monitor can block a statement or mask a column in real time. The cost is availability. For every client that uses the proxy, the database is only as available as the proxy in front of it. A passive network tap watches copies of the same traffic without that risk, but it can’t block anything, and on TLS connections it reads nothing unless it holds the keys.

We’d run two of these together: a proxy for attribution and enforcement, and the engine’s own log left on as a cross-check for any connection that reached the database some other way.

What should a DAM record hold?

A DAM record should let you answer an auditor’s question without opening a second system. That means the person or workload behind the query and the account it ran as, the client application and source address, the statement, the columns it returned, the row count, what policy decided, and a session ID that ties the query to the rest of that connection.

A few of those fields do more work than they look:

  • The identity, in two parts. The person or agent, and the database account the statement executed as. Behind a BI tool or a proxy the two differ, and the record needs both.
  • The statement as the client sent it and as it reached the database. When something in between rewrote it, by adding a row limit or a filter, the difference shows what the control did.
  • A normalized form with literals removed, or a fingerprint, so ten thousand runs of the same query group into one line.
  • The columns returned, with a classification label where you have one. “Read a column labeled email address” can drive an alert; “ran a SELECT” can’t.
  • Rows returned by the database and rows passed on to the client. A gap between the two proves a filter worked, and a spike in the first is how bulk reads show up.

Duration, timestamp and client application round it out. PostgreSQL’s own statement log gives you the text plus whatever log_line_prefix adds, such as the role and the application name. That names the right person only where everyone has their own role, and the statement log has no field for rows returned or for what a policy did.

Shared accounts and the attribution problem

Open a dashboard in a BI tool and its query reaches the database under the tool’s service account. Metabase, for one, can only use one credential per database, as our engineers explain in how we give cloud agents production access, and application servers behave the same way through connection pools, carrying every user’s requests over a handful of connections that one generic account opened. The database credits that account with everything.

Fixing it takes the application’s cooperation. Something has to carry the person’s identity alongside the query, and the two common carriers are a comment appended to the SQL text and a parameter on the database connection. Looker, for example, can pass the viewer’s email as an extra JDBC parameter. A monitor in the path reads the identity, records it next to the service account, and can apply that person’s policy rather than the tool’s.

A proxy in front of the database creates a second mismatch. It authenticates to the database with its own credential, so the engine’s log shows that credential on every query, whoever sent it. Expected, and useful. The proxy log becomes your record of who, the engine log your record that nothing arrived another way, and a statement in the engine log with no matching session in the proxy log is a connection that bypassed the proxy.

Database activity monitoring for AI agents and machine identities

An AI agent querying a database is a machine identity doing a person’s work. Cloud agents usually connect with an API key or a service account, so the database records the same account whoever launched the agent. Coding agents on a laptop often reuse the engineer’s credentials, and then the engineer gets the credit, with no sign that an agent wrote the query.

Neither record survives an investigation. What helps is recording two identities on each query, the agent and whoever launched it, and knowing they carry different weight. An agent platform can prove which agent session is calling, for example with a signed OIDC token, while the person behind it is asserted by the platform, which you’ve chosen to trust. Our guide to AI agent identity covers how agents authenticate without static secrets and how the delegation is recorded.

Each record should also say whether the caller was a human or a machine. With that one field you can pull every agent query during an incident, set an agent’s reads beside its owner’s, and alert on writes by machine identities in production. Exact query text makes a poor baseline for agents, since a model writes each query fresh from a prompt. Watch what the queries touch and how much they return instead.

Cursor runs cloud agents against its infrastructure through Formal. Roy Xu, on its security team:

“We’ve limited the amount of data that those cloud agents can access and we’re able to tie that back to the specific user who is using that cloud agent, which is a feature that I’m only aware of Formal having.”

— Roy Xu, Software Engineer, Security @ Cursor

Which DAM alerts to start with

Detection rules on a new DAM deployment should each point at something a person would look at the same day, usually an unauthorized read or a pull far bigger than normal. We’d start with these:

  • An identity reading a labeled column, such as email addresses or card numbers, that it has never read before.
  • Rows returned far above that identity’s usual volume, especially in a single query.
  • Permission and schema statements outside a change window: GRANT, ALTER ROLE, CREATE USER, DROP TABLE.
  • A burst of failed logins against one database, the easiest place to detect credential guessing.
  • Statements in the engine’s own log with no matching proxy session, if you run both.
  • Policy blocks per day as a trend. A jump means an attack, or a policy change that broke someone’s workflow, and you want to know either way.

Alerts on query text alone, like a DELETE with no WHERE clause, fire constantly in development and staging. Scope them to production and to an identity type first, for example writes by machine identities.

The activity log is sensitive data too

SELECT name, plan FROM customers WHERE email = 'ana@example.com' puts a customer’s email address in your activity log. Parameterized queries don’t avoid it: the PostgreSQL docs note that for the extended query protocol, log_statement output includes the values of the bind parameters. Forward it to a SIEM and the customer data now lives in a second system with a wider audience than the database had.

Strip or encrypt literals before anything is stored or exported. The normalized query keeps its shape, which is all that grouping and most alerts need, and an investigator who truly needs a value can go back to the source with approval.

Then decide who can delete a record. Native logs that sit on the database host can be rotated or truncated by the admins they’re meant to watch. Aurora’s activity streams keep admins out by design, and any DAM worth its cost should give you the same separation: write access for the collector, read access for security, and nobody in the monitored group able to edit either.

DAM vs database performance monitoring

“Database monitoring” usually means performance monitoring: query latency, throughput, active connections, lock waits, replication lag, and CPU, memory and disk on the server. Those tools are built for DBAs and SREs, and they often sample statements and drop the identity, because a slow query is slow whoever ran it.

DAM keeps every statement and puts the identity first, because anomaly detection on database access only works against one identity’s own history. Its metrics only make sense per person or workload: queries per hour, rows returned against that identity’s usual volume, first reads of a labeled column, permission changes, policy blocks. The two share raw material, and slow query logs sit somewhere in between, but a sampled performance tool makes a poor audit trail for an investigation. The query a sample drops can be the one an investigation needs.

DAM vs database access management

Access management decides who may connect and with which rights: privileged access management, short-lived credentials, just-in-time access with an approval. Database activity monitoring records what each person did once connected. You need both. Access control without monitoring can’t show what an approved person did with the access, and monitoring without access control records the same over-privileged accounts doing the same things.

A proxy that authenticates each person can do both on one hop, which is how Formal’s database access management works. Masking a column in the result is one of the actions DAM can take once it sits in the path; dynamic data masking has its own page. For the access side of the picture, start with what privileged access management is.

Database activity monitoring best practices

The order matters more than any single practice. Turning on enforcement before you know every route to a database breaks the routes nobody listed.

  1. List every route to each database: applications, BI tools, ETL jobs, AI agents, admins’ direct logins and break-glass accounts.
  2. Give each person and workload its own identity on the way in, and propagate end users from BI tools and apps.
  3. Collect in observe-only mode first. Write policies in dry-run, compare what they would have blocked against what actually happened, then enforce.
  4. Strip literals and set up export to your SIEM before widening collection to production.
  5. Close direct network paths to the database, keep native auditing on as the cross-check, and move the record out of the database admins’ reach.
  6. Review blocked queries and the top identities by rows returned every week, so drift shows up before an auditor finds it.

The database security guide covers the controls around this one, from network isolation to encryption and backups.

How does Formal approach database activity monitoring?

Formal monitors databases from inside the connection, through the Formal Connector, a proxy that speaks the wire protocol of Postgres, MySQL, MariaDB, Redshift, MongoDB, Snowflake, BigQuery, ClickHouse, DynamoDB and Redis, among others. Engineers, services and agents connect to it with their own Formal identity (idp:formal:human:alice@example.com as the Postgres username, for example), and the Connector authenticates to the database with a credential the client never sees. We run a Connector in front of our own production databases too.

Every query becomes a log entry. user.formal.user.type says human or machine, and user.formal.end_user.email carries the person behind a BI tool once end-user propagation is set up for Metabase, Looker, Omni or a custom app. The query is stored as received, as sent after any rewrite, normalized and fingerprinted. Rows returned by the database and rows sent to the client are separate fields, each returned column carries its data classification label, and triggered_policies records what policy did, including policies still in dry-run. Search uses Quickwit syntax. Two queries from the docs:

# Find queries blocked by a policy
event_type:request AND triggered_policies.type:block

# Complex: Find non-admin users accessing PII tables
(request.query.received:"users_pii" OR request.query.received:"customers_sensitive") AND NOT user.formal.user.groups:admin

Policies act on the same traffic: blocking or rewriting a query before it reaches the database, and masking or filtering rows on the way back. Each TCP connection becomes a session holding its queries, bind parameters and policy actions, and a session that’s still open can be cut off from the session details page, aborting whatever query is in flight.

For the log hygiene problem above, a log schema strips SQL literals before Formal stores or exports the log. This one, from the docs, applies to a single resource:

resource "formal_log_schema" "strip_customer_queries" {
  name      = "strip-customer-queries"
  scope_cel = "log.source == \"connector\" && log.resource.id == \"${formal_resource.customers.id}\""

  path {
    name      = "log.request.query"
    strip_sql = true
  }
}

The stored query then shows values_stripped: true and none of its original values. Logs stay searchable for as long as the account is active and can be forwarded to AWS S3, Google Cloud Storage, Azure Blob Storage, Datadog, Splunk or Panther. Policy evaluation inputs, kept for 0 to 30 days, let you backtest a new policy against past traffic; fine-grained Connector logs explains how retention is set per resource. At Cursor, the deployment handles 40M+ logs per week (case study).

Two limits to plan around. The Connector only records traffic that goes through it, so a client holding the database’s own credentials and a network route to it won’t show up, which is why the cross-check and the closed network paths above matter. And the AI risk score Formal computes for sessions is limited to SSH and Kubernetes; database sessions don’t get one. Setup for the two most common engines is on the Postgres and Snowflake pages, and our Metabase zero-day write-up makes the case for monitoring at the data layer after a real BI vulnerability.