This isn’t a case study. It’s a workshop packed into a blog post, and you can run it on your own Cozystack installation to see how the platform behaves and where it might fit into your projects. In about two hours, without leaving the terminal, we’ll build a system that catches card fraud in real time, and then we’ll give it a truly bad day: ten times the usual traffic, a crashed primary database server and a live migration of a virtual machine with payments flowing through it.
Everything runs on Cozystack, an open-source platform for building clouds and a CNCF Incubating project. Cozystack turns your servers into a ready-made cloud with managed Kubernetes, databases, message brokers, GPU as a Service and more.
One note before we start: the fraud detection here is a teaching example, not a product. Its job is to give the story a plot. What we’re really after is a close look at the platform and a feel for how it would fit your own work.
What we will build
When you pay by card in a store, the terminal asks the bank that issued the card whether the payment can go through. The program that answers is called a switch. In many banks it’s a legacy application that has sat on the same virtual machine for years, and nobody wants to touch it: if it ain’t broke, don’t fix it. Ours is no exception. It approves every payment under $5,000, which makes life very easy for fraudsters.
We’re not going to rewrite the switch, of course. We’ll build a payment check around it instead, roughly like this:
The switch stays as it is; everything else is built around it
The switch sends every payment to Kafka. The scoring service (scorer in the code) checks it against the card’s recent payment history, which lives in Redis, and posts its decision back to Kafka. The switch writes every decision to a journal, no matter who made it, and the cases service moves each journal entry into PostgreSQL, from where it shows up on the fraud team’s dashboard. On top of all that, a language model explains in plain words why a payment was declined. Front-line support needs this: customers will call the bank to ask why their card didn’t work, and someone has to tell them.
The design rests on three properties.
First, the switch never waits longer than it can afford. If the scorer has not answered within 400 milliseconds, the switch decides on its own, using the logic hard-coded into it. Banks call this stand-in processing, and it’s the difference between a slow fraud check and a processing outage. A slow check lets fraudulent payments slip through at peak hours. An outage lets nothing through at all, honest customers buying groceries included.
Second, the journal gets written no matter who made the decision, so you can always compare what the switch told the terminals with what ended up in the database. The two have to match.
Third, card data stays inside our cluster. Even the language model that writes explanations for support staff runs right next to the other services and never calls out to the internet.
Materials and documentation
The full guide, with every command and file, is in the public aenix-org/cozystack-workshop repository, in the fraud/ folder. It is available in English and in Russian. The same repository has materials from our other workshops and labs:
-
en/laptop/is a workshop on moving a virtual machine from VMware to Cozystack; -
en/laptop/labs/has sixteen short labs, from ordering your own Kubernetes cluster from the catalog to OpenBao, ClickHouse, MongoDB and live migration of virtual machines; -
fraud/app/holds the source code of every part of the fraud system, including the scoring rules, which are the most fun to experiment with.
Along the way we’ll lean on the Cozystack documentation.
All commands in this post run from the fraud/ folder of the cloned repository. In the terminal recordings you’ll see ~/workshop instead; that’s what the folder was called on the environment I recorded on.
Setting up the environment
This post grew out of a workshop we’ve already run in several cities, where our team prepared everything in advance. Each participant got a ready tenant with the legacy switch VM already running, a Kubernetes cluster, a GitLab account and a login on a bastion VM with all the tools installed (virtctl, kubectl and so on). Here you’ll do that prep yourself, on your own Cozystack cluster and your own laptop. It takes about half an hour.
You’ll need Cozystack 1.7 or newer and platform admin rights, because we’re going to create a tenant. If you don’t have Cozystack yet, start with the getting started guide. The cluster needs the replicated StorageClass and the ubuntu-24.04 image in the VM image catalog; a standard Cozystack install has both. On your computer you need kubectl, virtctl, git and curl. I gave the tenant a generous quota of 160 vCPU and 96 GiB of memory. Even at peak, the whole system uses about 10 GiB of RAM and around 20 vCPU.
The tenant and a working copy of the manifests
All the YAML manifests for setup live in fraud/instructor/. They use the placeholder dallasXX instead of a tenant name, so first pick a name and make a copy of the manifests with the placeholder replaced. In the examples the tenant is called fraud1, and by Cozystack convention its namespace is tenant-fraud1:
git clone https://github.com/aenix-org/cozystack-workshop.git cd cozystack-workshop/fraud export NAME=fraud1 T=tenant-fraud1 mkdir -p ~/fraud-env for f in instructor/*.yaml; do sed "s/tenant-dallasXX/$T/g; s/dallasXX/$NAME/g" "$f" > ~/fraud-env/$(basename "$f") done The tenant is created inside the root tenant, tenant-root. It won’t need its own monitoring in this guide, so we switch that off to save memory. You can do it in the Cozystack dashboard or, as the admin, with a single command:
kubectl apply -f - <<EOF apiVersion: apps.cozystack.io/v1alpha1 kind: Tenant metadata: {name: $NAME, namespace: tenant-root} spec: monitoring: false resourceQuotas: {cpu: "160", memory: 96Gi} EOF kubectl -n tenant-root get tenants.apps.cozystack.io $NAME -w Once the tenant reaches READY True, create a separate kubectl context for it. Every command in this post that talks to the platform goes through the tenant context. The easiest way is to copy the admin context and make the tenant’s namespace its default:
kubectl config set-context tenant \ --cluster=$(kubectl config view --minify -o jsonpath='{.contexts[0].context.cluster}') \ --user=$(kubectl config view --minify -o jsonpath='{.contexts[0].context.user}') \ --namespace=$T The switch and your own cluster
Now let’s create the switch VM and the cluster. switch-vm.yaml describes the switch’s virtual machine. Its disk is created from the ubuntu-24.04 image, and on first boot cloud-init downloads, installs and starts the auth-switch service. At the end of the same file is the switch service that terminals use to reach the machine. cluster.yaml orders a managed Kubernetes cluster called fraud from the Cozystack catalog. Since version 1.7, a cluster’s worker nodes are described by a separate KubernetesNodes application, and our file asks for one node, with autoscaling allowed to add a second one under load:
kubectl --context tenant apply -f ~/fraud-env/switch-vm.yaml -f ~/fraud-env/cluster.yaml kubectl --context tenant get vminstances,kubernetes -w The VM starts in a couple of minutes; the cluster takes a little longer. When it reaches READY True, grab its kubeconfig from the secret Cozystack creates and name the context fraud:
kubectl --context tenant get secret kubernetes-fraud-admin-kubeconfig \ -o jsonpath='{.data.admin\.conf}' | base64 -d > ~/fraud-env/fraud.kubeconfig KUBECONFIG=~/fraud-env/fraud.kubeconfig kubectl config rename-context \ "$(KUBECONFIG=~/fraud-env/fraud.kubeconfig kubectl config current-context)" fraud export KUBECONFIG=~/.kube/config:~/fraud-env/fraud.kubeconfig kubectl --context fraud get nodes You can also download the same file from the cluster’s page in the Cozystack console, under Secrets. It points to the cluster API at an external address like https://kubernetes-fraud.<tenant domain>, so it works from your own computer too.
Traffic and the model
Two more files go into the nested cluster. terminals.yaml creates the fraud namespace and, inside it, the endpoints ConfigMap with the addresses of Kafka, Redis, PostgreSQL and the switch in your tenant (these addresses are why we substituted the tenant name earlier), the traffic ConfigMap set to twenty payments per second, and the terminals pod that plays the role of the stores. prepull.yaml runs a one-off job that pulls the llama.cpp image onto the node in advance, so you don’t have to wait for it in part two.
kubectl --context fraud apply -f ~/fraud-env/terminals.yaml -f ~/fraud-env/prepull.yaml Our imaginary terminals start sending payments right away: the switch is already running and, for now, approves everything.
A Git repository and Flux
In part one the platform will pull our service definitions from Git, so it’s best to create the repository now. Any Git host the cluster can reach over HTTPS will do: GitLab, GitHub or Gitea. The repository needs a platform/ folder, and the two files we just applied by hand go into it right away. That way Flux, on its very first run, finds everything that’s already running described in Git and doesn’t delete anything to bring the cluster in line with the repository.
git clone https://<your-git>/<you>/fraud-infra.git ~/fraud-infra mkdir -p ~/fraud-infra/platform cp ~/fraud-env/cluster.yaml ~/fraud-infra/platform/kubernetes.yaml cp ~/fraud-env/switch-vm.yaml ~/fraud-infra/platform/switch-vm.yaml cd ~/fraud-infra && git add platform && git commit -m "Initial infrastructure" && git push To let the platform read the repository, create a read-only token on your Git host. In GitLab, a deploy token or a project access token with the read_repository scope will do. Then create three Flux objects in the tenant’s namespace: a secret with the token, a GitRepository source and a Kustomization that applies the platform/ folder. Flux itself is already running in the platform. The serviceAccountName field points to the service account Cozystack creates for every tenant. As a result, Flux applies the files with the tenant’s permissions rather than the platform admin’s and can’t do anything the tenant itself isn’t allowed to.
kubectl --context tenant create secret generic git-flux --from-literal=username=<login> --from-literal=password=<token> kubectl --context tenant apply -f - <<EOF apiVersion: source.toolkit.fluxcd.io/v1 kind: GitRepository metadata: {name: infra} spec: interval: 1m url: https://<your-git>/<you>/fraud-infra.git ref: {branch: main} secretRef: {name: git-flux} --- apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: {name: platform} spec: interval: 1m sourceRef: {kind: GitRepository, name: infra} path: ./platform prune: false targetNamespace: $T serviceAccountName: $T EOF kubectl --context tenant get kustomization platform When platform shows READY True, everything is wired up: once a minute Flux pulls the latest main and applies the platform/ folder.
The fraud team’s dashboard
The fraud dashboard is a web page we will deploy in part two. The simplest way to open it is a port forward: run kubectl --context fraud -n fraud port-forward svc/dashboard 8080 and open http://localhost:8080 in your browser. If you want a permanent address, as we had at the workshop, put your domain into ~/fraud-env/dashboard-ingress.yaml and apply the file through the tenant context: it publishes the dashboard through the platform’s ingress with a Let’s Encrypt certificate. In this post I use the address of my own environment, https://fraud.austin03.workshop.aenix.io; yours will be localhost:8080 or your own domain.
Part 0. Looking around: a switch that approves everything
After setup we have two kubectl contexts:
$ kubectl config get-contexts CURRENT NAME CLUSTER AUTHINFO NAMESPACE fraud fraud fraud-admin fraud * tenant platform austin03 tenant-austin03 Through the tenant context we talk to the Cozystack platform and order virtual machines, databases and the cluster itself. Through the fraud context we work with the nested Kubernetes cluster where the fraud services will run. Let’s see what we already have:
$ kubectl --context tenant get vminstances,kubernetes NAME READY AGE VERSION switch True 26m f379a04795e8 NAME READY AGE VERSION fraud True 26m 7c18a8ec4e4d $ kubectl --context tenant get resourcequota NAME REQUEST LIMIT AGE tenant-quota requests.cpu: 4525m/16, ... limits.cpu: 30258m/160, limits.memory: 42104Mi/96Gi 29m $ kubectl --context fraud -n fraud get pods NAME READY STATUS RESTARTS AGE prepull-explainer-2s24n 0/1 Completed 0 23m terminals-7cf5b9b59-6hfzv 1/1 Running 0 23m The switch and the cluster are in place, part of the quota is already in use, and the terminals pod is running in the fraud namespace. It stands in for stores across the country and sends the switch twenty payments per second. The prepull-explainer pod in Completed state is left over from setup: it is the job that pulled the llama.cpp image onto the node in advance.
Now let’s look inside the switch VM. Open the console with virtctl --context tenant console vm-instance-switch, or with the button on the VM’s page (the VNC tab) in the Cozystack dashboard. The login and password, ubuntu/ubuntu, are set by cloud-init in switch-vm.yaml; if the screen stays blank, press Enter. Here’s the switch’s log:
$ journalctl -u auth-switch --no-pager -n 3 Nov 23 03:28:34 switch auth-switch[650]: 5s: 100 authorizations, 0 declined, stand-in 0.0%, p99 0 ms Nov 23 03:28:39 switch auth-switch[650]: 5s: 100 authorizations, 0 declined, stand-in 0.0%, p99 0 ms In five seconds the switch handled a hundred authorizations, declined none of them and spent zero milliseconds on each. It doesn’t ask anyone and waves through anything up to $5,000.
Looking around: both contexts, the switch and the cluster are in place, and payments are already flowing
Now let’s check that fraudulent payments really do get past a switch like this. The fraud/manifests/ folder has an attack manifest that runs three schemes at once. The first is card testing, where fraudsters check stolen cards with tiny payments. The second is impossible travel: a card just used in Lagos pays for something in Chicago two minutes later, and no human covers that distance that fast. In the third, fraudsters walk through a bank’s BIN range, trying sixty of its card numbers in a row.
$ kubectl --context fraud apply -f manifests/04-attack.yaml job.batch/attack created $ kubectl --context fraud -n fraud logs job/attack --tail=4 attack: impossible travel on card …4653 from Charlotte attack: impossible travel on card …5504 from Chicago 5s: sent 30, approved 30, declined 0, errors 0, timeouts 0, p99 10.1 ms 5s: sent 21, approved 21, declined 0, errors 0, timeouts 0, p99 10.1 ms The switch approved all thirty fraudulent payments, because none of them was over $5,000. That’s our starting point: the system runs, but it protects nobody.
In the recording, keep an eye on the approved column: every single payment goes through.
An attack on a switch with no fraud check: every payment goes through
Part 1. Infrastructure in a Git repository
Everything we order from the platform is described in files in Git. We connected the repository to Flux during setup, so about a minute after changes land in main, Flux applies them as the tenant’s service account and the service we ordered starts coming up.
From here on we work in our clone of the repository, ~/fraud-infra, and order three managed services from the Cozystack catalog. Redis will remember each card’s recent activity: how often, where and for how much it was used. Kafka will carry the switch’s requests, the scorer’s decisions and the payment journal. PostgreSQL, with two instances, a primary and a replica, will store every transaction and a record of every check.
We’ll create Redis in the Cozystack dashboard first, then move the same declaration into Git; from that moment on, the repository is the source of truth. The form in the dashboard asks for the name features, one replica, a 1Gi disk on replicated storage and authentication turned off. In Git it looks like this:
# platform/redis.yaml apiVersion: apps.cozystack.io/v1alpha1 kind: Redis metadata: name: features spec: replicas: 1 size: 1Gi storageClass: replicated authEnabled: false Kafka and PostgreSQL we’ll write straight in YAML, following the documentation (Kafka, PostgreSQL). In Cozystack 1.7, Kafka runs in KRaft mode without ZooKeeper, so the declaration only has the broker and the topics:
# platform/kafka.yaml apiVersion: apps.cozystack.io/v1alpha1 kind: Kafka metadata: name: kafka spec: kafka: replicas: 1 size: 5Gi storageClass: replicated resourcesPreset: c1.small topics: - {name: auth.requests, partitions: 8, replicas: 1, config: {}} - {name: auth.decisions, partitions: 8, replicas: 1, config: {}} - {name: auth.journal, partitions: 8, replicas: 1, config: {}} Notice that the auth.requests topic has eight partitions. We’ll see why that matters in part four.
In the PostgreSQL declaration we ask for two instances, a fraud user and a fraud database that the user owns. No need to set a password: Cozystack generates one and puts it into the postgres-cases-credentials secret, from which we will hand it to the services in part two.
# platform/postgres.yaml apiVersion: apps.cozystack.io/v1alpha1 kind: Postgres metadata: name: cases spec: replicas: 2 size: 2Gi storageClass: replicated resourcesPreset: t1.micro users: fraud: {} databases: fraud: roles: admin: [fraud] Add the files to the repository, push them to main and watch what happens on the platform:
$ kubectl --context tenant get kafka,redis,postgres NAME READY AGE VERSION kafka Unknown 42s 744a68a3a447 NAME READY AGE VERSION features True 42s a0db0b4ba6d4 NAME READY AGE VERSION cases Unknown 42s ebc4944b1a9e Ordering services through Git: push, and a minute later the resources start coming up
Redis came up almost at once, PostgreSQL is still assembling its cluster, and Kafka can take noticeably longer than the rest. While they come up, let’s see what the platform did with our declarations. Each one became a Helm release, and each release in turn created resources for the operator that runs that service. PostgreSQL is run by the CloudNativePG operator, which decides on its own which pod is the primary and which is the replica:
$ kubectl --context tenant get hr NAME AGE READY STATUS kafka-kafka 6m True ... kubernetes-fraud ... postgres-cases ... $ kubectl --context tenant get pods -l cnpg.io/cluster=postgres-cases -L role NAME READY STATUS RESTARTS AGE ROLE postgres-cases-1 1/1 Running 0 119s primary postgres-cases-1-initdb-kx66m 0/1 Completed 0 2m24s postgres-cases-2-join-lkqts 1/1 Running 0 98s Now for the most telling GitOps experiment: what happens if someone changes by hand something that Git describes? Let’s delete Redis but leave its declaration in the repository:
$ kubectl --context tenant delete redis features redis.apps.cozystack.io "features" deleted $ kubectl --context tenant get redis -w NAME READY AGE VERSION Unknown 292y <unknown> <-- the object is deleted features Unknown 0s <unknown> <-- ...and immediately created again features True 56s a0db0b4ba6d4 About a minute later Redis was back. Once a minute Flux compares what is in Git with what is on the platform and recreates anything missing, so manual changes that contradict the repository don’t last long.
Redis deleted by hand comes back in about a minute
Part 2. The switch starts asking before it approves
With the data services ready, we deploy three applications into our own cluster: the scorer itself, the cases service that writes the journal into the database, and the fraud dashboard. All three are deliberately simple, a stripped-down model of a real fraud system.
First, let’s hand the services the database password. Cozystack generated it when it created PostgreSQL and keeps it on the platform, while the cases service and the dashboard need it in our cluster. This command copies the fraud user’s password from the platform secret into a cases-db secret in the nested cluster:
kubectl --context fraud -n fraud create secret generic cases-db \ --from-literal=password="$(kubectl --context tenant get secret postgres-cases-credentials -o jsonpath='{.data.fraud}' | base64 -d)" Now we can deploy the applications:
$ kubectl --context fraud apply -f manifests/02-scoring.yaml deployment.apps/scorer created deployment.apps/cases created deployment.apps/dashboard created service/dashboard created The scorer already knows where to find Kafka, Redis and PostgreSQL: their addresses are in the endpoints ConfigMap we created during setup. Tenant services are reachable from the nested cluster by their usual names, because the fraud cluster runs on the same network. The switch in the VM, however, knows nothing about the scorer yet. So let’s open the VM console with virtctl again, give the switch the Kafka address and restart it:
sudo sed -i 's#^KAFKA_BOOTSTRAP=.*#KAFKA_BOOTSTRAP=kafka-kafka-kafka-bootstrap:9092#' /etc/auth-switch/env sudo systemctl restart auth-switch journalctl -u auth-switch --no-pager -n 3 The broker’s short name is enough, because the tenant’s domain is in the VM’s DNS search list, so kafka-kafka-kafka-bootstrap resolves to the right address.
switch started in SCORING mode HTTP listening on :8080 5s: 111 authorizations, 0 declined, stand-in 0.0%, p99 272 ms SCORING mode means the switch now sends every payment to Kafka and waits for the scorer’s decision, and if there is no answer within 400 milliseconds, it decides on its own using its old rule. For the first few seconds latency is noticeable, while the Kafka connections are still being set up. Within half a minute things settle down, as the dashboard’s metrics show. I read them from my environment’s address; for you it will be http://localhost:8080/metrics through the port forward, or your own domain.
$ curl -s https://fraud.austin03.workshop.aenix.io/metrics | grep "^fraud_" | head -12 fraud_authorizations_per_second 9.7 # still ramping up to ~20 fraud_declines_per_second 0.3 fraud_stand_in_ratio 0 fraud_decision_latency_p50_seconds 0.0117 # ~12 milliseconds per decision fraud_transactions_stored 582 fraud_alerts_total 18 fraud_scorer_lag_messages 8 fraud_cases_lag_messages 6 fraud_journal_entries 588 fraud_journal_missing 6 The recording shows the whole switch-over: the applications deploy, the switch moves to Kafka and starts working in SCORING mode, and the first metrics appear.
Turning the check on: the switch moves to Kafka, decisions take about 12 ms
Now every payment goes through Kafka to the scorer and back, and the terminal gets an answer in about twelve milliseconds. The journal barely lags behind the flow of payments: the six entries that have not reached the database yet disappear from the fraud_journal_missing counter within a minute.
All that’s left is to teach the system to explain its declines. A support agent needs a reason they can read out to a customer who calls asking why their card payment failed. A small language model writes it: Qwen2.5 0.5B Instruct, run by llama.cpp. The model runs on an ordinary CPU inside our cluster and does not call any external service; on startup the pod downloads its weights once, about 400 MB. The llama.cpp image is already on the node thanks to the setup job, so the only wait is for the weights:
$ kubectl --context fraud apply -f manifests/03-explainer.yaml $ kubectl --context fraud -n fraud rollout status deploy/explainer --timeout=5m deployment "explainer" successfully rolled out The explainer’s address was set in cases from the start, and cases was waiting for it to appear. With normal traffic there are only a handful of declines, so the model only gets real work during an attack. Let’s run the attack again:
$ kubectl --context fraud apply -f manifests/04-attack.yaml job.batch/attack created $ kubectl --context fraud -n fraud logs job/attack -f attack: card testing on card …1176: 36 probes of $0.50–$3.00 attack: impossible travel on card …4653 from Charlotte ... 5s: sent 30, approved 24, declined 6, errors 0, timeouts 0, p99 125.0 ms 5s: sent 21, approved 6, declined 6, errors 0, timeouts 0, p99 125.0 ms 5s: sent 12, approved 0, declined 6, errors 0, timeouts 0, p99 125.0 ms The first few test payments go through, because a single tiny payment looks like any other and the pattern only shows after several attempts. But by the middle of the attack the scorer is declining every fraudulent payment: it spots card testing at about the sixth payment and the BIN range walk at about the eighth card. The fraud_alerts_total counter has grown to 23, and for 19 of them the model has already written a plain-language explanation.
The rules the scorer uses live in a short Go file, rules.go. If you want to change the thresholds, start there, not in the YAML.
The same attack that sailed through in part zero is now declined after the first few attempts:
The repeated attack: the first attempts get through, then fraudulent payments are declined
Part 3. The analysts want ClickHouse and an S3 bucket
The fraud check works, and then, as always, the analysts show up. They want to run any query they like against the payment journal without putting load on the system payments go through. In a public cloud we’d open the console, find a managed ClickHouse and order it in a couple of clicks. Here we do the same thing with one file in the same repository:
# platform/clickhouse.yaml apiVersion: apps.cozystack.io/v1alpha1 kind: ClickHouse metadata: name: analytics spec: replicas: 1 shards: 1 resourcesPreset: t1.medium size: 5Gi storageClass: replicated clickhouseKeeper: enabled: false users: fraud: password: Fraud2026 ClickHouse Keeper lets several ClickHouse replicas coordinate with each other, but we have only one replica, so we turn it off. The ClickHouse docs for Cozystack say so, and details like this are what separate someone who read the documentation from someone who copied the first manifest they found. Push the file, wait a couple of minutes and connect to ClickHouse with its own client, clickhouse-client, which is already installed in the pod:
$ kubectl --context tenant exec -it chi-clickhouse-analytics-clickhouse-0-0-0 -c clickhouse -- \ clickhouse-client --user fraud --password Fraud2026 The operator names ClickHouse pods chi-<name>-clickhouse-<shard>-<replica>. If your pod is named differently, find it with kubectl --context tenant get pods | grep chi-.
ClickHouse can read Kafka on its own, no extra code required. The SQL file manifests/05-analytics.sql creates three objects. The first, a table on the Kafka engine, reads the auth.journal topic. The second, the payments table on the MergeTree engine, stores the payments. The third, a materialized view, moves every new row from the first table into the second:
CREATE TABLE journal_stream (raw String) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka-kafka-kafka-bootstrap:9092', kafka_topic_list = 'auth.journal', kafka_group_name = 'clickhouse-analytics', kafka_format = 'JSONAsString', kafka_max_block_size = 1000, kafka_poll_max_batch_size = 1000; CREATE TABLE payments (...) ENGINE = MergeTree ...; CREATE MATERIALIZED VIEW payments_stream_mv TO payments AS SELECT ... FROM journal_stream; The easiest way to load the file is with the same client, on standard input:
kubectl --context tenant exec -i chi-clickhouse-analytics-clickhouse-0-0-0 -c clickhouse -- \ clickhouse-client --user fraud --password Fraud2026 --multiquery < manifests/05-analytics.sql A couple of minutes later the payments table is answering queries and holds everything the switch has seen since the check was turned on:
$ clickhouse-client ... -q "SELECT count(*) AS stored_payments FROM payments" 329860 -- the journal has been growing since the check was turned on, so your number will differ $ clickhouse-client ... -q "SELECT merchant, count(*) AS declines FROM payments WHERE decision = 'DECLINE' GROUP BY merchant ORDER BY declines DESC LIMIT 10" ClickHouse reads Kafka directly: stored payments and the merchants with the most declines
The file has three more example queries: merchants with the most declines, declines per minute, and the share of payments the switch approved without a check, also per minute. They all work on the same data the scorer uses for its decisions. ClickHouse, the dashboard and cases each read the journal in their own Kafka consumer group, so they do not get in each other’s way.
The last step in this part is an S3 bucket for reports. It’s ordered the same way, with a declaration in Git: platform/bucket.yaml describes a reports bucket with one user, analytics.
# platform/bucket.yaml apiVersion: apps.cozystack.io/v1alpha1 kind: Bucket metadata: name: reports spec: users: analytics: {} A bucket user here isn’t a person but a separate pair of S3 access keys that opens only this bucket. Cozystack creates the keys and puts them into the bucket-reports-analytics-credentials secret. The easiest place to read them is the Cozystack dashboard, on the reports bucket’s page under Secrets. For the query you need accessKey, secretKey and bucketName, plus your platform’s object storage address; on my environment that is s3.workshop.aenix.io. The query below has placeholders instead of the keys:
INSERT INTO FUNCTION s3('https://s3.workshop.aenix.io/<bucket>/daily-report.csv', '...






