Happy Dussehra! May good always win. Merry Christmas! Warm wishes from Vizag. Happy New Year! Here’s to a great year ahead.

DevOps

Sprint 6 project, Part 2: Core ERP Data and Events

Build the ERP's data layer on the Part 1 platform: SchemaHero tables on RDS, Amazon MSK with event contracts in Apicurio, Cadence workflows on CloudNativePG, a ClickHouse reporting feed, CubeFS documents, and a seed generator that fills two tenants.

15 min read

  • SchemaHero
  • Amazon RDS
  • CloudNativePG
  • Apache Kafka
  • Amazon MSK
  • Apicurio Registry
  • Cadence
  • ClickHouse
  • CubeFS
  • Kubernetes
  • OpenTofu
  • Python

This is Part 2 of the six-part build in the Sprint 6 project overview. Part 1 left you an EKS cluster, an RDS database, Karpenter, Argo CD, two Capsule tenants and Istio. Now the ERP gets something to run on: tables defined in Git with SchemaHero, events on Kafka (Amazon MSK) with contracts in Apicurio Registry, durable workflows in Cadence, a reporting feed into ClickHouse, documents on CubeFS, and a seed generator that fills two tenants with data.

Where this part fits. This part builds the data and event layer (marked Part 2 on the overall diagram). Open the zoomable Sprint 6 architecture or read the Overview.

Overall Sprint 6 architecture

What this is and is not. This is engineering guidance, not legal or financial advice. It is a reference blueprint: the intended flow and the wiring between the tools. Versions, chart keys, environment variable names and API fields change between releases, so each section gives a check to confirm them on your version. If you hit a bug or a mismatch, use the “Suggest a correction” link on this page.

What you build, and in what order

Part 2 architecture. SchemaHero applies table definitions from Git to RDS PostgreSQL, which the ERP services use. The services publish events to Kafka on MSK, checked against schemas in Apicurio Registry. ClickHouse consumes the topics for reports. Kafka events start Cadence workflows, whose activities call the ERP services and whose history is stored in a CloudNativePG PostgreSQL cluster. The services store documents in CubeFS.

One image, the layers of this part. Open the zoomable diagram, or download it as SVG or PNG.

Two databases are used on purpose. RDS holds the business records, because they must outlive the cluster. CloudNativePG runs a PostgreSQL cluster inside Kubernetes for Cadence’s history, which is operational state that can be rebuilt and does not need to be a managed-service line item. The ERP never writes to the Cadence database, and Cadence never reads the ERP’s.

Flow in seven steps: apply the schema, create Kafka topics, register contracts, run a Cadence workflow, feed ClickHouse, store a document in CubeFS, then run the seed generator.

  1. MSK and the topics
  2. Tables with SchemaHero
  3. Event contracts in Apicurio
  4. Cadence on CloudNativePG
  5. The ClickHouse feed
  6. Documents on CubeFS
  7. The seed generator
  8. Troubleshooting, cost, cleanup, checklist

1. MSK and the topics

Part 1 did not create Kafka. Add it to the OpenTofu stack with the same pattern as the Sprint 5 build: Standard brokers, SASL/SCRAM over TLS, a customer-managed key, and the credentials in Secrets Manager under a name that starts with AmazonMSK_.

resource "aws_msk_cluster" "erp" {
  cluster_name           = "erp"
  kafka_version          = var.kafka_version      # list with: aws kafka list-kafka-versions
  number_of_broker_nodes = 3
  broker_node_group_info {
    instance_type   = "kafka.m7g.large"
    client_subnets  = module.vpc.private_subnets
    security_groups = [aws_security_group.msk.id]
    storage_info { ebs_storage_info { volume_size = 100 } }
  }
  client_authentication { sasl { scram = true } }
  encryption_info {
    encryption_at_rest_kms_key_arn = aws_kms_key.platform.arn
    encryption_in_transit { client_broker = "TLS" }
  }
}
resource "aws_msk_scram_secret_association" "erp" {
  cluster_arn     = aws_msk_cluster.erp.arn
  secret_arn_list = [aws_secretsmanager_secret.msk_erp.arn]   # name starts with AmazonMSK_, customer-managed key
}

The security group allows port 9096 (SCRAM over TLS) only from the node security group. Put a value in the secret before the association, and read it into the cluster with external-secrets or a Secret you create by hand for the lab. Then the topics. Name them for the event, key them by tenant, and keep the first set small:

Topic Key Carries
erp.orders tenant and order id order created, confirmed, shipped
erp.invoices tenant and invoice id invoice posted, paid
erp.stock tenant and item id stock moved
erp.approvals tenant and request id approval requested, decided
kafka-topics.sh --bootstrap-server $BOOTSTRAP --command-config client.properties \
  --create --topic erp.orders --partitions 6 --replication-factor 3 \
  --config min.insync.replicas=2 --config retention.ms=604800000

Repeat for the other three. Check: kafka-topics.sh --list shows all four, and a console producer and consumer pass a test message through erp.orders.

2. Tables with SchemaHero

SchemaHero turns table definitions into migrations. Install the operator, give it the RDS connection, then commit tables to Git.

kubectl krew install schemahero      # or follow the brief's install section
kubectl schemahero install

The connection reads the RDS URI from a Secret (the managed master password from Part 1 lives in Secrets Manager; for the lab, create a dedicated erp_migrator role and put its URI in the Secret):

apiVersion: v1
kind: Secret
metadata: { name: rds-postgres, namespace: erp }
stringData:
  uri: postgresql://erp_migrator:<password>@<instance>.<region>.rds.amazonaws.com/erp?sslmode=require&connect_timeout=10&application_name=schemahero
---
apiVersion: databases.schemahero.io/v1alpha4
kind: Database
metadata: { name: erp, namespace: erp }
spec:
  connection:
    postgres:
      uri: { valueFrom: { secretKeyRef: { name: rds-postgres, key: uri } } }

One schema carries every tenant, with the tenant id as part of each key and row-level security on top, so a missing filter cannot leak rows:

apiVersion: schemas.schemahero.io/v1alpha4
kind: Table
metadata: { name: orders, namespace: erp }
spec:
  database: erp
  name: orders
  schema:
    postgres:
      primaryKey: [tenant_id, id]
      columns:
        - { name: tenant_id, type: text, constraints: { notNull: true } }
        - { name: id, type: uuid, default: gen_random_uuid() }
        - { name: customer_id, type: uuid, constraints: { notNull: true } }
        - { name: status, type: text, constraints: { notNull: true }, default: "'draft'" }
        - { name: total, type: numeric(18,2), constraints: { notNull: true } }
        - { name: created_at, type: timestamp, default: now() }
      indexes:
        - { columns: [tenant_id, status], name: orders_tenant_status }

Add customers, items, invoices and approvals in the same style. Row-level security is a SQL statement that SchemaHero’s table definition does not express, so apply it once with a migration job:

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.tenant_id', true));

The ERP services set app.tenant_id on each connection from the validated token. In CI, plan on pull requests (schemahero plan) and apply on merge, as the brief shows. Check: kubectl -n erp get tables shows each table deployed, and \d orders in psql lists the columns, the index and the policy.

3. Event contracts in Apicurio

Run Apicurio Registry with PostgreSQL storage, using a database on the CloudNativePG cluster from the next section or a separate small one. The environment variable names below are the 3.x style; confirm them against the image’s documentation.

apiVersion: apps/v1
kind: Deployment
metadata: { name: apicurio, namespace: data }
spec:
  replicas: 1
  selector: { matchLabels: { app: apicurio } }
  template:
    metadata: { labels: { app: apicurio } }
    spec:
      containers:
        - name: registry
          image: quay.io/apicurio/apicurio-registry:<current 3.x>
          ports: [{ containerPort: 8080 }]
          env:
            - { name: APICURIO_STORAGE_KIND, value: sql }
            - { name: APICURIO_STORAGE_SQL_KIND, value: postgresql }
            - { name: APICURIO_DATASOURCE_URL, value: "jdbc:postgresql://<host>:5432/apicurio" }
            - { name: APICURIO_DATASOURCE_USERNAME, valueFrom: { secretKeyRef: { name: apicurio-db, key: user } } }
            - { name: APICURIO_DATASOURCE_PASSWORD, valueFrom: { secretKeyRef: { name: apicurio-db, key: password } } }

The events are JSON, because ClickHouse reads them as JSONEachRow, so the contracts are JSON Schema artifacts. Register one and turn on a backward compatibility rule:

curl -s -X POST $REGISTRY/apis/registry/v3/groups/erp/artifacts -H 'Content-Type: application/json' -d '{
  "artifactId": "erp.invoices-value",
  "artifactType": "JSON",
  "firstVersion": { "version": "1", "content": { "contentType": "application/json", "content": "{\"type\":\"object\",\"required\":[\"event_time\",\"tenant_id\",\"invoice_id\",\"amount\",\"status\"],\"properties\":{\"event_time\":{\"type\":\"string\"},\"tenant_id\":{\"type\":\"string\"},\"invoice_id\":{\"type\":\"string\"},\"amount\":{\"type\":\"number\"},\"status\":{\"type\":\"string\"}}}" } }
}'
curl -s -X POST $REGISTRY/apis/registry/v3/groups/erp/artifacts/erp.invoices-value/rules \
  -H 'Content-Type: application/json' -d '{"ruleType":"COMPATIBILITY","config":"BACKWARD"}'

The registry does not sit in the broker’s path, so it cannot block a bad message on the wire. The contract is enforced in two places: the CI job for each service fetches the latest schema and validates its sample events, and the producers validate before sending. Check: registering a second version that removes a required field is refused with a compatibility error, and a version that adds an optional field is accepted. The API paths and field names changed between 2.x and 3.x, so check them against your registry’s OpenAPI document at /apis/registry/v3.

4. Cadence on CloudNativePG

First the PostgreSQL cluster Cadence stores its history in:

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata: { name: cadence-pg, namespace: cadence }
spec:
  instances: 2
  storage: { size: 20Gi, storageClass: gp3 }
  bootstrap: { initdb: { database: cadence, owner: cadence } }

Then the Cadence chart, with persistence pointed at that cluster. The chart publishes example values for PostgreSQL; start from those and change only the host and secret. The key names move between chart releases, so compare with the chart’s values.yaml.

helm repo add cadence-workflow https://cadenceworkflow.github.io/cadence-charts
helm install cadence cadence-workflow/cadence -n cadence -f cadence-values.yaml

Register a domain for the ERP and write the approval workflow as ordinary code. A purchase approval waits for a person for as long as it takes, then continues:

func PurchaseApproval(ctx workflow.Context, req ApprovalRequest) (string, error) {
    ao := workflow.ActivityOptions{ScheduleToStartTimeout: time.Minute, StartToCloseTimeout: time.Minute}
    ctx = workflow.WithActivityOptions(ctx, ao)
    if err := workflow.ExecuteActivity(ctx, NotifyApprover, req).Get(ctx, nil); err != nil {
        return "", err
    }
    var decision string
    sig := workflow.GetSignalChannel(ctx, "decision")
    sel := workflow.NewSelector(ctx)
    sel.AddReceive(sig, func(c workflow.Channel, _ bool) { c.Receive(ctx, &decision) })
    sel.AddFuture(workflow.NewTimer(ctx, 72*time.Hour), func(workflow.Future) { decision = "escalated" })
    sel.Select(ctx)
    err := workflow.ExecuteActivity(ctx, RecordDecision, req.ID, decision).Get(ctx, nil)
    return decision, err
}

A small consumer reads erp.approvals events of type “requested” and starts one workflow per request, using the request id as the workflow id so a replayed event cannot start a second one. The RecordDecision activity calls the ERP service API through the mesh, so Istio and the tenant checks apply to it like any other caller. Month-end close is the same pattern with more steps. Check: start a workflow, kill the worker pod, start it again, then send the decision signal; the workflow finishes and cadence workflow show lists the full history.

5. The ClickHouse feed

Install ClickHouse as the ClickHouse brief describes, on Karpenter nodes in the clickhouse namespace, with Keeper for coordination. The feed is a Kafka table engine plus a materialised view, one pair per topic:

CREATE TABLE erp.invoices
(
    event_time DateTime, tenant_id String, invoice_id String, amount Decimal(18, 2), status String
) ENGINE = MergeTree ORDER BY (tenant_id, event_time);

CREATE TABLE erp.invoices_queue
(
    event_time DateTime, tenant_id String, invoice_id String, amount Decimal(18, 2), status String
) ENGINE = Kafka
SETTINGS kafka_broker_list = '<broker>:9096', kafka_topic_list = 'erp.invoices',
         kafka_group_name = 'clickhouse-invoices', kafka_format = 'JSONEachRow',
         kafka_sasl_mechanism = 'SCRAM-SHA-512', kafka_security_protocol = 'sasl_ssl';

CREATE MATERIALIZED VIEW erp.invoices_mv TO erp.invoices AS SELECT * FROM erp.invoices_queue;

The SASL user and password go in ClickHouse’s server configuration under the kafka section, not in the table definition; the setting names for SCRAM are worth confirming for your version. Check: after the seed generator runs (section 7), SELECT tenant_id, count(), sum(amount) FROM erp.invoices GROUP BY tenant_id returns one row for each tenant.

6. Documents on CubeFS

Install CubeFS from its chart as the CubeFS brief describes, with the object gateway enabled so services speak S3. CubeFS runs its own metadata and data nodes, so give them Karpenter nodes with local or EBS storage and the CriticalAddonsOnly toleration is not needed.

helm upgrade --install cubefs ./cubefs -f cubefs-values.yaml -n cubefs --create-namespace
aws --endpoint-url http://objectnode.cubefs.svc:17410 s3 mb s3://documents
echo "test" > t.txt && aws --endpoint-url http://objectnode.cubefs.svc:17410 s3 cp t.txt s3://documents/acme/t.txt

Documents go under a prefix per tenant, documents/<tenant>/…, and access is checked in the service before it hands out a pre-signed URL. Backups of the volume go to S3 in Part 6. Check: the object round-trips (s3 cp back and compare), and a second tenant’s service role cannot list the first tenant’s prefix.

7. The seed generator

A short Python program creates two tenants of data, publishes the matching events, and uploads a few sample PDFs:

import json, os, random, uuid, datetime as dt
import psycopg
from confluent_kafka import Producer

p = Producer({"bootstrap.servers": os.environ["BOOTSTRAP"], "security.protocol": "SASL_SSL",
              "sasl.mechanisms": "SCRAM-SHA-512", "sasl.username": os.environ["KUSER"],
              "sasl.password": os.environ["KPASS"]})

def seed(tenant, n_orders):
    with psycopg.connect(os.environ["DATABASE_URL"]) as db:
        for _ in range(n_orders):
            oid, total = uuid.uuid4(), round(random.uniform(50, 5000), 2)
            db.execute("INSERT INTO orders (tenant_id, id, customer_id, status, total) VALUES (%s,%s,%s,'confirmed',%s)",
                       (tenant, oid, uuid.uuid4(), total))
            ev = {"event_time": dt.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), "tenant_id": tenant,
                  "invoice_id": str(oid), "amount": total, "status": "posted"}
            p.produce("erp.invoices", key=f"{tenant}:{oid}", value=json.dumps(ev))
    p.flush()

for t, n in (("acme", 500), ("globex", 300)):
    seed(t, n)

Run it as a Kubernetes Job in a tenant namespace so the traffic goes through the mesh and the network policy from Part 1. Check: 500 and 300 rows in orders per tenant, the same counts in ClickHouse a minute later, and one Cadence workflow per seeded approval.

8. Troubleshooting

Symptom Likely cause Fix
MSK association rejected Secret name not prefixed AmazonMSK_, default key, or no value Use the customer key and put a value first
Producer SASL authentication failed Wrong port or mechanism Port 9096 with SCRAM-SHA-512 and TLS
Topic creation times out Security group blocks the client Allow 9096 from the node group
SchemaHero table stuck planned Plan not approved or connection failing kubectl describe table; check the Secret and port 5432
Migration blocked by a lock Long transaction on the table Retry in a quiet window; keep migrations small
Apicurio will not start Storage env names differ in your image Compare with that version’s documentation
Schema upload returns 404 v2 and v3 API paths differ Read the OpenAPI document served by the registry
Cadence pods crash on start Persistence values wrong or schema not set up Check the chart’s schema job and the database credentials
Workflow stuck, no worker Task list name mismatch Worker and starter must use the same domain and task list
ClickHouse table empty Consumer group stuck or SASL missing Check system.kafka_consumers; set credentials in server config
ClickHouse parse errors Event field types differ from the table Match the contract; use kafka_skip_broken_messages only to diagnose
CubeFS object gateway refuses Wrong key or endpoint Create an access key with the CubeFS tooling and use path-style addressing

Cost note

Read on 3 December 2026, US East list prices (Mumbai prices were not read): Amazon MSK kafka.m7g.large is $0.204 per broker hour, so three brokers are about $0.61 an hour, roughly $447 a month; the MSK pricing page’s own example prices storage at $0.060 per GB-month. The RDS instance is the figure from the Overview (about $123 a month, from a third-party aggregator). ClickHouse, CubeFS and Cadence run on Karpenter nodes whose price depends on the instance types chosen; EC2 prices were not read. MSK is the main line item, so create it at the start of a build session and destroy it when you stop.

Cleanup

Reverse order: remove the ClickHouse, Cadence, CubeFS and Apicurio releases and their volumes; delete the SchemaHero tables only after you have decided to lose the data (SchemaHero drops nothing on its own, but you can delete the namespace); then destroy MSK with OpenTofu. Delete the topics only if the cluster stays.

helm -n cadence uninstall cadence && kubectl -n cadence delete cluster.postgresql.cnpg.io cadence-pg
helm -n cubefs uninstall cubefs
kubectl -n data delete deploy apicurio
# MSK last of the paid items
cd infra/foundation && tofu destroy -target=aws_msk_scram_secret_association.erp -target=aws_msk_cluster.erp

Design notes and version checks

  • Nothing here was run on AWS. The snippets follow the documentation and the briefs on this site; the likeliest differences are chart value names, Apicurio’s environment and API paths, and ClickHouse’s SASL settings.
  • JSON, not Avro. Events are JSON so ClickHouse can read them directly. Apicurio holds JSON Schema contracts and does not sit in the broker’s path, so enforcement happens in CI and in the producers.
  • Why two PostgreSQL stacks. RDS for the system of record; CloudNativePG for Cadence history and the Apicurio store. This follows the sprint’s rule of using a managed service where records must survive the cluster.
  • Row-level security is applied by a migration the tables do not express; the services must set app.tenant_id on each connection, or reads return nothing. Pooling in front of RDS needs a mode that keeps that setting per transaction.
  • Idempotency. The workflow id comes from the request id, so repeated events do not start duplicates; consumers of other topics should treat events as at-least-once.
  • Cadence versions. The Go client and server versions must match the chart’s release; check the chart’s compatibility note.
  • Kuadrant, AGE and the rest of the Overview’s open items are not touched here; they are decided in Parts 4 and 5.

Setup checklist

  • 1. MSK: done when the cluster is ACTIVE, the SCRAM secret is associated and a test message passes through erp.orders.
  • 2. Topics: done when erp.orders, erp.invoices, erp.stock and erp.approvals exist with three replicas.
  • 3. Schema: done when every table is deployed and the row-level policy is listed.
  • 4. Contracts: done when an incompatible schema version is refused and a compatible one accepted.
  • 5. Cadence: done when a workflow survives a worker restart and finishes after the signal.
  • 6. ClickHouse: done when seeded events appear per tenant in erp.invoices.
  • 7. CubeFS: done when an object round-trips and another tenant cannot list the prefix.
  • 8. Seed: done when both tenants have their rows, events and workflows.

Tools used

SchemaHero, CloudNativePG, Apache Kafka, Apicurio Registry, Cadence, ClickHouse, CubeFS, Strimzi (the self-run alternative to MSK), OpenTofu.

What comes next

Part 3 builds the model path: MatrixHub, Karpenter GPU nodes, vLLM served through KServe, Kubeflow Trainer and Pipelines, Unsloth and DeepEval gates, and the GPU or CPU decision on prices read that day. Back to the Overview.

Spotted something wrong or out of date?Suggest a correction. I review every suggestion before changing the page.

EmailRSS