The user wants a design for a "multi-tenant API schema registry."
This registry needs to support three specific API protocols: GraphQL, gRPC, and REST.
Key features required:
- Compatibility Semantics: How to handle changes without breaking clients.
- Notification Channels: Alerting relevant parties about changes.
- SLAs (Service Level Agreements): Performance and reliability guarantees.
- Billing Integration: Tracking usage and charging tenants.
High-Level Architecture:
- It needs a core storage layer for schemas.
- It needs parsers/validators for GraphQL, Protobuf (gRPC), and OpenAPI (REST).
- It needs a multi-tenant isolation mechanism.
- It needs a change log/event stream.
Section 1: Core Schema Model & Multi-Tenancy
- Concept: Tenant isolation is paramount. Every resource belongs to a Tenant ID.
- Naming: Needs unique identifiers per tenant (namespaces).
- Storage: Separate logical partitions (or physical if strict isolation is needed, but logical is usually enough for SaaS). Blob storage (S3) for raw files, DB (PostgreSQL/DynamoDB) for metadata/search.
Section 2: Protocol Specifics (The "Big Three")
- REST (OpenAPI/Swagger): JSON/YAML based.
- GraphQL (SDL): Schema Definition Language. Needs to handle federation potentially, but core schema first.
- gRPC (Protobuf): Needs a
.proto file registry. Imports are tricky here (dependencies).
Section 3: Compatibility Semantics (The "Safe Change" Logic)
- This is the intellectual core.
- REST: Check for breaking changes (removing fields, changing types). Tools like
oasdiff.
- GraphQL: Check for breaking changes (removing fields, making args non-null). Tools like
graphql-inspector. Handling "evolution" vs "breaking".
- gRPC: Protobuf has built-in rules, but stripping fields is still bad if not done carefully. Use specific library to compare descriptors.
- Versioning: URL path versioning (REST), Date/Field masking (gRPC), or just safe evolution (GraphQL).
Section 4: Notification Channels
- Event-Driven: Webhooks, Kafka/SQS integration.
- Polling: ETag headers.
- User-facing: Email/Slack alerts on breaking changes.
Section 5: SLAs (Service Level Agreements)
- Availability: 99.9% typical.
- Latency: Read (fetch schema) must be fast. Write (validation) can take longer.
- Durability: Schemas must never be lost.
Section 6: Billing Integration
- Metering: What do we charge for?
- Number of schemas?
- Number of API calls (read/write)?
- Advanced features (breaking change detection)?
- Storage size?
- Integration: Stripe/Chargebee. Usage reports.
Drafting the Design - Iteration 1 (Mental Outline):
- Intro: High-level diagram description.
- Tenant Model:
TenantID everywhere.
- Schemas: How to store them? Git-based or DB-based? Let's suggest a hybrid (DB for state, Git/S3 for artifact).
- Compatibility Engine: A modular plugin system. Input = Schema A, Schema B. Output = List of Breaking Changes.
- Notifications: Webhook system is best. Pub/Sub pattern.
- Billing: Usage metrics pipeline -> Billing provider.
Refining the "Compatibility" Section:
- Need to define strict vs. loose modes.
- REST:
POST /schemas returns 200 OK or 400 Breaking Change.
- GraphQL: Need to handle federated subgraphs? Keep it simple for now, focus on single schema compatibility.
Refining "gRPC":
- The hard part with gRPC is dependencies (imports). The registry must manage a file tree, not just single files.
- Solution: Treat upload as a "commit" of a directory structure.
Structure of the Response:
- System Architecture Overview: Diagram description and component breakdown.
- Multi-Tenancy & Data Model: How data is isolated and structured.
- Protocol Support (The Polyglot Layer): Handling REST, GraphQL, gRPC specifics.
- Compatibility & Validation Engine: The rules logic.
- Notification & Governance: Events and alerts.
- SLA & Operational Guarantees: Performance tiers.
- Billing & Metering: Monetization strategy.
Self-Correction/Refinement during thought process:
- Initial thought: Just store the text.
- Correction: No, we must parse it. To check compatibility, we need the Abstract Syntax Tree (AST) or resolved descriptors. The registry acts as a compiler would.
- Billing: Don't just bill per schema. Bill per "validation request" or "consumption" (SDK generation?). Let's stick to standard SaaS metrics: Active Schemas + Bandwidth.
Detailed Technical Specs:
- Storage: Postgres (Metadata) + S3 (Raw Artifacts + Compiled binaries like FileDescriptorSet).
- API: Use gRPC for the registry API itself? Or REST? Let's propose a dual protocol for the registry itself to "eat your own dogfood."
Final Polish: Ensure the distinction between GraphQL, gRPC, and REST handling is clear in the "Compatibility" section, as they evolve differently (e.g., GraphQL relies on non-nullability for safety, Protobuf on field numbers).
Let's write the solution.
This design outlines a comprehensive, production-grade Universal Schema Registry capable of handling REST (OpenAPI), GraphQL (SDL), and gRPC (Protobuf) within a multi-tenant architecture.
1. High-Level Architecture
The system acts as the "Source of Truth" for API contracts. It is event-driven, decoupling schema ingestion from validation and distribution.
Core Components:
- Ingestion Layer: Multi-protocol endpoints to accept schema definitions.
- Parsing & Linting Engine: Language-specific parsers (Swagger Core,
protoc, graphql-js) to validate syntax and enforce standards (e.g., breaking changes, naming conventions).
- Metadata Store: PostgreSQL for structured metadata (versions, tenants, SLAs) + S3/Blob Storage for the raw schema files.
- Compatibility Engine: The logic core that compares diffs between schema versions.
- Notification Service: Fan-out system for webhooks, emails, and pub/sub events.
- Billing Meter: Usage aggregation pipeline.
2. Multi-Tenancy & Data Model
Isolation is logical, not physical, to maximize resource efficiency.
Entity Hierarchy
- Organization (Tenant): The billing entity.
- Project: Logical grouping (e.g.,
checkout-service, user-profile). Maps to a namespace.
- API Spec: The actual schema artifact.
Data Model (PostgreSQL)
CREATE TABLE organizations (
id UUID PRIMARY KEY,
slug VARCHAR(64) UNIQUE, -- e.g., "acme-corp"
plan_tier VARCHAR(32), -- 'free', 'startup', 'enterprise'
billing_provider_id VARCHAR(128) -- Stripe Customer ID
);
CREATE TABLE api_specifications (
id UUID PRIMARY KEY,
org_id UUID REFERENCES organizations(id),
project_name VARCHAR(128),
spec_type VARCHAR(16), -- 'REST', 'GraphQL', 'gRPC'
spec_name VARCHAR(128), -- 'Petstore', 'UserService'
current_version_hash VARCHAR(64),
retention_days INTEGER, -- SLA config
is_active BOOLEAN DEFAULT true
);
CREATE TABLE schema_versions (
id UUID PRIMARY KEY,
spec_id UUID REFERENCES api_specifications(id),
version_semver VARCHAR(32), -- '1.2.0'
content_hash VARCHAR(64),
file_location_s3 VARCHAR(256),
compatibility_level VARCHAR(16), -- 'NONE', 'BACKWARD', 'FORWARD', 'FULL'
registered_at TIMESTAMPTZ DEFAULT NOW()
);
3. Protocol Support & Compatibility Semantics
The most critical feature is preventing breaking changes. The registry enforces different rules per protocol type.
A. REST (OpenAPI / Swagger)
- Format: JSON/YAML.
- Compatibility Strategy: Backward Compatibility.
- Breaking Change Rules:
- Cannot remove a required field.
- Cannot change a data type (e.g.,
string to integer).
- Cannot change
readonly to writeonly.
- Implementation: Uses
openapi-diff libraries.
B. GraphQL (SDL)
- Format:
.graphql / .gql.
- Compatibility Strategy: Forward & Backward (Full). GraphQL relies on non-breaking evolution.
- Breaking Change Rules:
- Cannot remove a field from a type that is returned by a query.
- Cannot remove a Query/Mutation entry point.
- Cannot change a field from Nullable to Non-Nullable (breaks existing clients expecting null).
- Exceptions: Enum value removal (breaking), Input type field removal.
- Implementation: Uses
graphql-inspector or apollo-schema-diff.
C. gRPC (Protocol Buffers)
- Format:
.proto.
- Compatibility Strategy: Backward & Forward (Wire compatible).
- Breaking Change Rules:
- Cannot change a field number.
- Cannot change a field type (int32 -> string).
- Cannot remove a field number (should be marked
reserved).
- Cannot change
repeated to singular or vice versa on existing fields.
- Implementation: Uses
buf CLI or protoc with breaking change detector plugins.
4. Notification Channels
When a schema changes or a breaking change is detected, the system triggers notifications via a Fan-out Pattern.
-
Webhooks:
- Tenants configure a
POST endpoint.
- Payload includes:
{ event_type: "schema.registered", spec_name: "...", version: "...", diff_url: "..." }.
- Retries: Exponential backoff (3 attempts).
-
Event Bus (Kafka/SQS/PubSub):
- For internal microservices (e.g., to trigger API Gateway updates or SDK generators).
- Topic:
org.{org_id}.schema.events.
-
Email/Slack:
- Administrative alerts for approval workflows or critical breaking changes.
5. Service Level Agreements (SLAs)
The registry must commit to performance to ensure it doesn't block CI/CD pipelines.
| Metric | Target (SLA) | Implementation Strategy |
|---|
| Availability | 99.95% | Multi-AZ deployment, Read-Replicas for DB. |
| Ingestion Latency | < 500ms (P95) | Async processing. API returns 202 Accepted + Polling URL if validation takes longer than 100ms. |
| Fetch Latency | < 50ms (P95) | Aggressive CDN caching for public keys/schemas; Redis cache for hot metadata. |
| Retention | Configurable | Tier-based. Enterprise keeps history forever; Free tier keeps 30 days. |
6. Billing Integration
Billing is event-driven and integrated via Stripe (or similar).
Metering Metrics
- Schema Storage: GB-months of data stored.
- API Calls: Number of read/writes to the registry.
- Advanced Features: Extra charge for "Custom Linting Rules" or "High Retention."
Implementation Flow
- Metering Service: Writes usage events to a high-throughput queue (Kafka).
- Aggregator: A background worker sums usage per tenant per hour/day.
- Stripe Integration:
- Subscriptions: Fixed monthly fee handled via Stripe Subscriptions.
- Usage: Reported via Stripe Metered Billing API (
stripe.subscriptionItems.createUsageRecord).
// Conceptual Billing Meter Logic
async function reportUsage(orgId, metricType, quantity) {
const stripeCustomerId = await db.getStripeId(orgId);
await stripe.subscriptionItems.createUsageRecord(
stripeSubscriptionItemId,
{ quantity: quantity, timestamp: Math.floor(Date.now() / 1000) }
);
}
7. API Workflow Example
Scenario: A developer registers a new OpenAPI spec.
- POST /v1/orgs/{org_id}/specs/rest
- Body: Raw YAML/JSON.
- Headers:
X-Compatibility-Strategy: BACKWARD.
- Validation Phase:
- Parser checks syntax.
- System fetches the latest version from DB.
- Diff Engine: Compares old vs. new.
- Decision:
- If Breaking: Returns
409 Conflict with detailed error message (e.g., "Field 'id' type changed").
- If Safe: Proceeds.
- Storage:
- Upload raw file to S3 (
/orgs/acme/petstore/1.0.1.yaml).
- Insert metadata row in Postgres.
- Side Effects:
- Publish event to Kafka
schema.updated.
- Trigger Webhooks.
- Increment billing counter (
api_writes).
- Response:
201 Created.
8. Tech Stack Recommendation
- Language: Go or Rust (High performance for parsers) or Java (Excellent ecosystem for Swagger/Protobuf).
- Database: PostgreSQL (Reliability) + Redis (Caching).
- Storage: AWS S3 / Azure Blob.
- Queue: Kafka or RabbitMQ.
- Infrastructure: Kubernetes (for scaling the parsing workers independently of the API).