Schema-Registry Backed JSON Validation Gateway Architecture
This architecture designs a JSON Validation Gateway that enforces schema validation for API payloads using a centralized Schema Registry. It supports version negotiation, schema compatibility rules, and rollout guardrails to ensure safe evolution of schemas in microservices or event-driven systems. The gateway acts as a transparent proxy: it validates incoming JSON requests/responses against registered schemas and forwards only valid traffic to upstream services.
Key goals:
- Safety: Prevent invalid data from propagating.
- Evolvability: Allow backward-compatible schema changes without breaking clients.
- Observability: Monitor validation failures and rollout health.
- Scalability: Handle high-throughput with low latency.
1. High-Level Architecture
[Client] --> [API Gateway / Load Balancer] --> [JSON Validation Gateway (Cluster)]
|
| (gRPC/HTTP)
v
[Schema Registry] <--> [Compatibility Service] <--> [Metrics DB / Prometheus]
|
| (HTTP/gRPC)
v
[Backend Services] <--> [Observability Stack] (Jaeger, Prometheus, Grafana)
Core Components
| Component | Purpose | Tech Suggestions |
|---|
| Schema Registry | Stores schemas with metadata (subject, version, compatibility). | Apicurio Registry (open-source, JSON Schema native) or Confluent Schema Registry (with JSON Schema plugin). |
| JSON Validation Gateway | Validates payloads, negotiates versions, applies guardrails. | Envoy Proxy (WASM/ Lua filters for custom logic) + Go/Rust sidecar for heavy validation; or custom Go service with go-jsonschema. |
| Compatibility Service | Evaluates schema evolution rules during registration. | Integrated with Registry or separate FastAPI/Go microservice using jsonschema + fastjsonschema. |
| Rollout Guardrails | Traffic splitting, canaries, failure thresholds. | Integrated via Envoy xDS or Istio; LaunchDarkly/Flagger for orchestration. |
| Observability | Metrics, traces, logs for validation & rollouts. | OpenTelemetry, Prometheus, Grafana Loki. |
2. Schema Registry Design
Schema Structure
Schemas are registered under a subject (e.g., user-v1, order-created-v2) using JSON Schema (draft-2020-12).
{
"schema": { /* JSON Schema object */ },
"metadata": {
"subject": "user-profile",
"version": 3,
"compatibility": "BACKWARD", // Enum: NONE, BACKWARD, FORWARD, FULL, TRANSITIVE
"description": "Added optional 'phone' field",
"tags": ["pii", "v2-rollout"],
"rolloutConfig": { "canaryWeight": 0.1, "maxFailures": 0.05 }
}
}
Registry APIs (HTTP/gRPC)
- POST /subjects/{subject}/versions: Register new schema version. Triggers compatibility check.
- GET /subjects/{subject}/versions/latest: Fetch latest compatible schema.
- POST /compatibility: Dry-run compatibility test between old/new schemas.
- GET /subjects/{subject}/versions/{version}: Fetch specific schema.
- DELETE /subjects/{subject}/versions/{version}: Soft-delete (tombstone).
Storage: PostgreSQL/CRDT (for multi-region) + Redis cache. Use content-based hashing (SHA-256 of schema) for deduplication.
3. Version Negotiation
Clients negotiate schema versions via headers or query params. Gateway resolves to the highest compatible version available.
Negotiation Flow
1. Client sends: POST /users with headers:
- `X-Schema-Subject: user-profile`
- `X-Schema-Version: >=2` // SemVer range or exact
- `Content-Type: application/json; schema=urn:ietf:wg:rest:json-schema#`
2. Gateway:
a. Extracts subject/version from header.
b. Queries Registry for candidate versions (e.g., `>=2 && compatible=true`).
c. Selects **highest version** passing compatibility (BACKWARD for requests, FORWARD for responses).
d. Responds with: `X-Schema-Version: 3` (negotiated).
3. Validates payload against negotiated schema.
Fallbacks:
- If no match:
422 Unprocessable Entity with X-Error: INCOMPATIBLE_SCHEMA.
- Default: Latest BACKWARD-compatible if client omits version.
Implementation: Gateway filter chain (Envoy Lua/WASM):
-- Pseudo-Lua in Envoy
local registry_client = grpc_client("schema-registry:8080")
local candidates = registry_client:find_versions(subject, client_version_range)
local negotiated = select_highest_compatible(candidates, direction="request")
local schema = registry_client:get_schema(subject, negotiated)
validate_json(payload, schema)
4. Compatibility Rules
Defines how new schemas evolve from previous versions. Checked on registration and negotiation.
Compatibility Types
| Type | Request Compatibility (Client → Server) | Response Compatibility (Server → Client) |
|---|
| NONE | No checks. | No checks. |
| BACKWARD | New schema reads old data (required fields unchanged; new fields optional). | Old clients read new data. |
| FORWARD | Old schema reads new data. | New clients read old data. |
| FULL | Backward + Forward. | Full. |
| TRANSITIVE | Compatible across all versions in chain. | Full chain. |
Enforcement Logic
-
On Registration: Compatibility Service simulates:
# Pseudo-Python with jsonschema
def check_backward(old_schema, new_schema, sample_old_data):
validator = Draft202012Validator(new_schema)
return all(validator.is_valid(instance) for instance in sample_old_data)
- Generate synthetic data from old schema (using
hypothesis-jsonschema).
- Fail registration if incompatible.
-
Evolution Rules (Automated):
| Allowed | Blocked |
|---|
| Add optional fields. | Remove fields, change types, make required → optional. |
Rename with aliases ("aliases": ["oldName"]). | Numeric precision loss (int → float). |
-
Config: Per-subject default (e.g., FULL for critical subjects).
5. Rollout Guardrails
Safely deploy new schema versions with progressive traffic exposure.
Guardrail Features
-
Canary Rollouts:
- On registration, new version starts with
rolloutConfig.canaryWeight: 0.1 (10% traffic).
- Gateway routes via weighted routing (Envoy
WeightedCluster).
-
Failure Thresholds:
- Monitor
validation_errors / total_requests < maxFailures (e.g., 5%).
- Metrics:
schema_validation_failures_total{subject,version,direction}.
- Auto-rollback: If threshold breached, pin traffic to previous version.
-
Traffic Splitting:
Version 2 (90%) | Version 3 (10%) --> Gateway splits based on client headers or random (sticky sessions via `X-Client-ID`).
-
Promotion API:
POST /subjects/{subject}/versions/{version}/promote
Body: { "weight": 1.0, "validate": true } // Promote to 100%, run final compat check.
-
Circuit Breakers:
- Per-version: Halt traffic if error rate > 10% for 1min.
- Global: Fallback to latest stable.
Orchestration: Integrate with Argo Rollouts or Flagger. Use Kafka/Redis for config propagation (xDS in Envoy).
Monitoring Dashboard (Grafana)
- Schema adoption:
requests_by_version.
- Error rates: Heatmap by subject/version.
- Alerts:
rate(validation_errors[5m]) > 0.05.
6. Gateway Implementation Details
Request/Response Pipeline (Envoy Filter Chain)
- Decode JSON.
- Negotiate schema version.
- Validate (compile schema to fast validator like
fastjsonschema for <1ms latency).
- Enrich headers (
X-Schema-Version).
- Route to backend (or reject).
- Post-Backend: Validate responses similarly.
Performance:
- Cache schemas in-memory (LRU, TTL=1h).
- Async validation with worker pool.
- Scale horizontally (Kubernetes HPA on CPU).
Security:
- mTLS between Gateway/Registry.
- Rate-limit per subject.
- Schema signing (JWT) for tamper-proof.
Edge Cases
- Polyglot Clients: Support Avro/Protobuf translation if needed.
- Nested Schemas: Recursive validation with refs.
- Multi-Region: Registry replication with CRDTs (e.g., CockroachDB).
7. Deployment & Onboarding
- Bootstrap: Register initial schemas via CI/CD (GitOps with schemas in repo).
- Testing:
schema-registry-cli for local mocks.
- Migration: Dual-write gateway during cutover.
This architecture ensures zero-downtime schema evolution with robust safety nets. Total latency overhead: ~2-5ms at p99. Prototype in Go+Apicurio for POC.
Questions? Let's iterate on specifics like integrations or code samples. 🕵️♂️