Blog homeKYC for AI AgentsIntegration guideEU AI Act checklistCompare
← Back to blog
· By

Building a KYA Architecture: Technical Blueprint for AI

A comprehensive technical blueprint for implementing Know Your Agent (KYA) compliance architecture for high-risk autonomous AI systems.

Preferred source on Google
Building a KYA Architecture
Table of Contents

TL;DR

  • A production KYA architecture has four decoupled layers: identity/certificate issuance (AWS KMS), API gateway scope enforcement, behavioral risk engine, and immutable WORM audit storage.
  • Each layer has a different build-vs-buy cost profile — the CA/identity layer is the most deceptively expensive to build correctly in-house.
  • Deployment should colocate gateway nodes near the KMS region to keep the certificate-verification latency budget low.
  • Roll out in four phases — shadow mode, single pilot agent, representative cohort, then fleet-wide — to avoid false-positive revocations at scale.
  • Root CA keys stay offline and never sign agent certificates directly; only intermediate CAs do, limiting blast radius on rotation or compromise.

What are the four layers of a Know Your Agent (KYA) architecture?

A production KYA architecture has four layers: an identity and certificate-issuance layer that issues X.509 certificates via a KMS-backed CA; an API gateway layer that enforces mTLS and validates each request against the certificate's encoded scope; a behavioral risk engine that scores every action against a rolling baseline in real time; and an immutable, WORM-protected audit store that records every identity, scope, and revocation event for regulatory evidence.

System Architecture Overview

Deploying autonomous AI agents in regulated sectors requires an architecture that bridges high-performance software execution with strict regulatory compliance. The Know Your Agent (KYA) technical blueprint consists of four decoupled layers:

  • Identity & Certificate Issuance Layer (AWS KMS + X.509 CA)
  • API Gateway & Scope Enforcement Layer (mTLS Proxy)
  • Behavioral Anomaly & Risk Engine (Rolling 30-Day Window)
  • Immutable Evidence & Audit Storage (WORM Postgres + QStash)

This document provides engineering teams with a production-grade specification for building or integrating a KYA architecture.

---

Layer 1: Cryptographic Identity & AWS KMS Integration

Every agent registered in the system receives a unique X.509 digital certificate. To enforce strict key hygiene, private keys are generated inside AWS KMS (RSA_2048) and are never exported to application memory.

The resulting certificate contains custom X.509 OID extensions encoding the agent's permitted scope, operator ID, and software digest.

---

Layer 2: API Gateway & Scope Enforcement

When the AI agent attempts to execute an action (e.g., approving a loan or submitting a trade), the API Gateway intercepts the request and validates three conditions:

  • mTLS Handshake: Confirms the client certificate is signed by Kakunin's intermediate CA and is not present on the Certificate Revocation List (CRL).
  • Scope Validation: Checks that the action parameters (e.g., €35,000 credit allocation) are within the certified limits embedded in the certificate.
  • Revocation SLA: Verifies that the agent's risk score remains below the pre-revocation threshold (0.75).

For step-by-step setup guides, refer to our KYC SDK Integration Documentation.

---

Layer 3: Behavioral Anomaly Engine (Rolling 30-Day Window)

The behavioral risk engine tracks every ingested event against a rolling 30-day statistical baseline. Kakunin computes an anomaly score using three composite metrics:

  • Frequency Anomaly (Sf): Z-score evaluation of event velocity over 5-minute sliding windows.
  • Payload Entropy (Se): Kullback-Leibler divergence of JSON payload schemas against baseline distributions.
  • Target Divergence (Sd): Categorical evaluation of requested API routes against historical frequency.

If the composite risk score >= 0.85, the engine triggers automated revocation, pushing a revocation signal to the CRL endpoints in under 60 seconds.

---

Layer 4: Immutable Audit Trail (WORM Enforcement)

To satisfy EU AI Act Article 12 and MiCA Article 70 requirements, all event records, risk score updates, and revocation actions are written to an append-only Write-Once-Read-Many (WORM) PostgreSQL table protected by database-level triggers blocking UPDATE and DELETE operations.

For complete regulatory mappings, consult our Regulatory Mapping Matrix.

Deployment Topology and Latency Budget

A KYA architecture is only viable if it does not become the bottleneck in an agent's decision loop. Because certificate signing and CA custody live in AWS KMS (eu-west-1), the primary control plane is anchored to that region, and every regulated entity's API Gateway nodes should be deployed in the same region or a low-latency adjacent one to avoid cross-region round trips on the hot path. For CASPs and financial AI operators trading or settling in the EU, this also keeps the enforcement boundary inside the same jurisdictional footprint as the underlying regulated activity, which simplifies data residency arguments under MiCA.

The end-to-end latency budget for a single enforced action breaks into four sequential costs: the mTLS handshake and CRL lookup at the gateway, the scope validation against the certificate's embedded OID extensions, the Upstash Redis rate-limit check, and a read of the agent's current composite risk score. In practice, session resumption on the mTLS layer and a Redis-backed local cache of the CRL bitmap keep the first two steps in the low single-digit milliseconds; the risk-score read is the more variable cost, since it depends on how recently the behavioral engine last recomputed that agent's score. Kakunin's design keeps risk scores warm in Redis rather than recomputing them synchronously per request, so gateway enforcement reads a cached score and the underlying recomputation happens asynchronously off the request path.

Edge placement matters less for the enforcement decision itself, which must stay close to KMS and the WORM audit store, and more for agents operating in latency-sensitive contexts such as high-frequency trading bots. For those, we recommend colocating the agent's execution environment in the same region as the gateway rather than pushing enforcement logic to a distant edge node, since a cross-region hop for every certified action will dominate the latency budget far more than anything inside the gateway itself.

Build vs. Buy: A Framework for Engineering Leadership

Engineering leaders evaluating whether to build a KYA stack in-house versus integrate an existing one should treat it as four separate build decisions, not one, because each layer has a different cost profile and a different regulatory blast radius if implemented incorrectly.

The identity and CA layer is the most deceptively expensive to build. Standing up a compliant certificate authority means not just calling KMS APIs, but designing an intermediate CA hierarchy, a CRL/OCSP distribution pipeline, custom X.509 extension schemas, and a revocation SLA your compliance team can defend to an auditor. Most teams underestimate this by treating it as "call KMS CreateKey" rather than "operate a CA."

  • Identity & CA layer: high build cost, high regulatory risk if the CA hierarchy or key custody chain is misconfigured — favor buying unless you already operate CA infrastructure elsewhere in the business
  • API Gateway & scope enforcement: moderate build cost; an existing mTLS proxy (Envoy, Kong) can be extended, but custom OID scope parsing and the 0.75 pre-revocation check are novel logic that need dedicated engineering time
  • Behavioral risk engine: highest ongoing maintenance cost — the 30-day rolling baseline and composite scoring model require continuous tuning as agent behavior drifts, which is easy to underinvest in after initial launch
  • WORM audit storage: lowest build cost — a Postgres trigger blocking UPDATE/DELETE is a few dozen lines of SQL — but the hardest to retrofit correctly after the fact, since any pre-existing mutable audit table has to be migrated without breaking chain-of-custody claims for past records

Total Cost of Ownership Considerations

Beyond initial build cost, the recurring cost that most teams miss is regulatory maintenance: MiCA and EU AI Act guidance continues to evolve, and a self-built compliance mapping has to be re-validated against every update. An integrated platform amortizes that maintenance across its entire customer base rather than requiring each engineering team to track it independently. For teams that decide to build, budget for a standing compliance-engineering liaison role, not just the initial implementation sprint — see our Regulatory Mapping Matrix for the categories of guidance that change most frequently.

Certificate Authority Resilience and Key Rotation

A KYA architecture's root of trust is only as resilient as its CA hierarchy's rotation and recovery procedures. Kakunin's root CA key stays offline in a dedicated KMS key with restricted IAM policy, and never signs agent certificates directly — it only signs intermediate CA certificates. This two-tier structure means routine key rotation and disaster recovery operate on intermediates, not the root, dramatically shrinking the blast radius of any single rotation event.

Intermediate CAs are rotated on a fixed schedule and dual-issued during the transition window: a new intermediate is created and cross-signed before the old one expires, so agents can be re-issued certificates from the new intermediate without a service interruption. Because AWS KMS never exports private key material, key rotation is really CA-certificate rotation — the underlying asymmetric key pair inside KMS can be regenerated and re-wrapped in a new certificate without ever touching plaintext key bytes.

  • Compromise response: revoke the affected intermediate CA at the root, propagate the revocation to all CRL/OCSP endpoints within the standard 60-second SLA, and force re-issuance of every certificate signed by that intermediate
  • Cross-region CRL/OCSP replication: revocation endpoints are replicated outside eu-west-1 so a regional AWS incident does not leave gateways unable to check certificate status — a stale or unreachable CRL should fail closed, not open
  • Backup scope: only KMS key ARNs, certificate metadata, and the audit trail are backed up — never key material, since it never leaves KMS in the first place
  • Recovery drills: intermediate CA failover should be rehearsed on a schedule, not just documented, since a rotation procedure that has never been executed against a live gateway is unverified

Horizontal Scaling of the Behavioral Risk Engine

The behavioral engine's 30-day rolling window creates a scaling problem distinct from typical stateless API scaling: each incoming event has to be compared against a statistical baseline that itself must stay current as new events arrive. Kakunin's approach partitions the ingestion pipeline by agent ID, so each agent's event stream and rolling baseline are processed independently and can be sharded across workers without cross-agent coordination.

Events arrive through QStash, which decouples ingestion from scoring — a burst of activity from one agent (or a fleet-wide spike, such as many agents reacting to the same market event) queues rather than blocking the gateway's synchronous enforcement path. Scoring workers are stateless and pull the rolling window's sufficient statistics from Redis rather than recomputing them from raw event history on every invocation, which keeps the marginal cost of scoring a new event roughly constant regardless of how much history sits behind it.

Under sustained high event volume, the three composite metrics scale differently. Frequency anomaly (Sf) is cheapest, since it only needs a rolling counter per 5-minute bucket. Payload entropy (Se) is the most compute-intensive, since KL-divergence against a baseline distribution requires maintaining a histogram per agent and recomputing divergence on each event; this is the component most worth batching, and Kakunin recomputes Se on a short debounce window rather than per-event when an agent's request rate exceeds a threshold, trading a small amount of detection latency for materially lower compute cost during bursts. Target divergence (Sd) sits in between, since it's a categorical lookup against historical route frequency that can be served from an in-memory cache refreshed on a fixed interval.

The practical ceiling on horizontal scale is not the scoring workers themselves — those scale linearly by adding shards — but the WORM audit write path, since every risk-score update and revocation event still has to be durably recorded. Batching audit writes per agent per short interval, rather than writing on every scored event, keeps this from becoming the throughput ceiling while still preserving a complete evidentiary trail.

Phased Rollout: From Pilot Agent to Fleet-Wide Enforcement

Rolling out a KYA architecture across an existing fleet of production agents carries real operational risk if enforcement is turned on all at once — a miscalibrated risk threshold or an unanticipated scope boundary can trigger false-positive revocations against agents already handling live regulated activity. A phased rollout keeps that risk bounded while still moving toward full enforcement on a defined timeline.

  • Phase 0 — Shadow mode: issue certificates and run the behavioral engine against real traffic, but do not enforce revocation. This phase exists purely to calibrate the 30-day baseline and confirm the 0.85 threshold and 0.75 pre-revocation warning behave as expected against your actual agent population before they can affect production traffic
  • Phase 1 — Single pilot agent: enable full enforcement, including automated revocation, on one low-blast-radius agent. This validates the entire chain end to end — certificate issuance, gateway enforcement, risk scoring, and the WORM audit trail — against a real production workload with a contained failure domain
  • Phase 2 — Representative cohort: expand to a small set of agents spanning your different scope profiles (e.g., a trading agent, a customer-facing agent, an internal automation agent), since each profile will produce a different baseline behavioral signature and may need threshold tuning
  • Phase 3 — Fleet-wide enforcement: extend to the remaining agent population, with the pilot and cohort data informing per-agent-class threshold adjustments rather than a single global threshold
  • Rollback criteria should be defined before Phase 1 begins, not improvised during it — a documented false-positive-rate ceiling that, if exceeded, reverts the affected agent class to shadow mode while thresholds are retuned

Observability and Alerting Across the Four Layers

A production KYA deployment needs monitoring at each of the four layers independently, because a failure in one layer can silently degrade the others without triggering an obvious outage. Certificate issuance failures at the KMS layer should alert immediately, since a stalled issuance pipeline means new agents can't onboard even though existing certified agents keep operating normally — an easy failure to miss if monitoring only watches gateway request success rates. Gateway-layer metrics should track mTLS handshake failure rates separately from application-level errors, since a spike in handshake failures often indicates a CRL propagation problem rather than a genuine agent misbehavior.

The risk engine's health is best measured by scoring latency and queue depth on its QStash-backed ingestion pipeline, not just by the risk scores it produces — a backlog in scoring means agents are operating on stale risk assessments, which is a materially different failure mode than the engine correctly scoring an agent as low-risk. Finally, the WORM audit layer should be monitored for write latency and, periodically, for a synthetic verification check that confirms UPDATE and DELETE attempts against a test row are still rejected — a control that has silently stopped enforcing is far more dangerous than one that was never implemented, because the team believes it's protected when it isn't.

FAQ

How long does a KYA architecture take to implement from scratch?

For a team building all four layers in-house, expect several months of dedicated engineering time, with the identity and CA layer typically taking the longest due to the operational rigor a compliant CA hierarchy requires. Integrating an existing platform rather than building compresses this substantially, since the CA, revocation infrastructure, and audit storage are already operational and the remaining work is scope configuration and gateway integration specific to your agents.

Does the 30-day rolling window mean new agents are unprotected for their first month?

No. A new agent's baseline is seeded conservatively and tightens as real event history accumulates, rather than leaving the agent unscored during the initial period. The engine can still detect gross anomalies — an entirely new agent suddenly issuing high-value transactions, for instance — against category-level baselines before its own 30-day history is fully built out.

What happens to an agent's in-flight actions if it is revoked mid-transaction?

Revocation blocks new certified actions at the gateway going forward; it does not retroactively unwind an action already committed before the revocation signal propagated. This is why the 60-second CRL/OCSP propagation SLA matters — it bounds the window of residual risk to a fixed, auditable interval rather than leaving it open-ended, and that interval itself is logged to the WORM audit trail as part of the incident record.

Can the risk thresholds (0.75 warning, 0.85 revocation) be customized per agent or per regulated activity type?

Yes, and the phased rollout approach described above is specifically designed to surface where per-agent-class tuning is needed. A high-frequency trading agent and a customer support agent will have structurally different baseline behavior, so applying one global threshold across both tends to produce more false positives than tuning thresholds to each agent class's actual behavioral profile.

Is the WORM audit table alone sufficient for MiCA Article 70 and EU AI Act Article 12 compliance?

The append-only audit table satisfies the immutability and traceability requirements those articles emphasize, but compliance also depends on what gets written to it — certificate issuance, scope decisions, every risk-score transition, and revocation events all need to be captured, not just high-level transaction outcomes. Consult the Regulatory Mapping Matrix for the specific event categories examiners expect to see represented in the trail.

Palash Bagchi
Published September 15, 2026

Founder of Kakunin, building cryptographic identity and compliance infrastructure for autonomous AI agents.

All articles →
Read more from the blog
Documentation →
API reference and guides