{"slug": "build-your-own-fraud-detection-on-cozystack-a-legacy-card-switch-gitops-an-llm", "title": "Build your own fraud detection on Cozystack: a legacy card switch, GitOps, an LLM and managed services", "summary": "A team at Aenix published a hands-on Cozystack workshop that builds a real-time card-fraud detection system around a legacy payment switch, wiring Kafka, Redis, PostgreSQL and a locally hosted language model into a GitOps-managed cluster. The setup keeps the switch's 400-millisecond stand-in processing as a fallback, journals every decision for reconciliation, and keeps card data and the LLM inside the cluster, then stress-tests it with 10x traffic, a crashed primary database and a live VM migration. The full commands and files are in the public aenix-org/cozystack-workshop repository.", "body_md": "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.\n\nEverything runs on [Cozystack](https://cozystack.io/), 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.\n\nOne 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.\n\nWhen 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.\n\nWe’re not going to rewrite the switch, of course. We’ll build a payment check around it instead, roughly like this:\n\n*The switch stays as it is; everything else is built around it*\n\nThe 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.\n\nThe design rests on three properties.\n\nFirst, 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.\n\nSecond, 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.\n\nThird, 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.\n\nThe full guide, with every command and file, is in the public [aenix-org/cozystack-workshop](https://github.com/aenix-org/cozystack-workshop) repository, in the [`fraud/`](https://github.com/aenix-org/cozystack-workshop/tree/master/fraud) folder. It is available [in English](https://github.com/aenix-org/cozystack-workshop/blob/master/fraud/README.md) and [in Russian](https://github.com/aenix-org/cozystack-workshop/blob/master/fraud/README.ru.md). The same repository has materials from our other workshops and labs:\n\n`en/laptop/`` en/laptop/labs/``fraud/app/`\nAlong the way we’ll lean on the [Cozystack documentation](https://cozystack.io/docs/v1.7/).\n\nAll 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.\n\nThis 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.\n\nYou’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](https://cozystack.io/docs/v1.7/getting-started/). 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.\n\nAll the YAML manifests for setup live in [`fraud/instructor/`](https://github.com/aenix-org/cozystack-workshop/tree/master/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`:\n\n```\ngit clone https://github.com/aenix-org/cozystack-workshop.git\ncd cozystack-workshop/fraud\nexport NAME=fraud1 T=tenant-fraud1\nmkdir -p ~/fraud-env\nfor f in instructor/*.yaml; do\n  sed \"s/tenant-dallasXX/$T/g; s/dallasXX/$NAME/g\" \"$f\" > ~/fraud-env/$(basename \"$f\")\ndone\n```\n\nThe 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:\n\n```\nkubectl apply -f - <<EOF\napiVersion: apps.cozystack.io/v1alpha1\nkind: Tenant\nmetadata: {name: $NAME, namespace: tenant-root}\nspec:\n  monitoring: false\n  resourceQuotas: {cpu: \"160\", memory: 96Gi}\nEOF\nkubectl -n tenant-root get tenants.apps.cozystack.io $NAME -w\n```\n\nOnce 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:\n\n```\nkubectl config set-context tenant \\\n  --cluster=$(kubectl config view --minify -o jsonpath='{.contexts[0].context.cluster}') \\\n  --user=$(kubectl config view --minify -o jsonpath='{.contexts[0].context.user}') \\\n  --namespace=$T\n```\n\nNow 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:\n\n```\nkubectl --context tenant apply -f ~/fraud-env/switch-vm.yaml -f ~/fraud-env/cluster.yaml\nkubectl --context tenant get vminstances,kubernetes -w\n```\n\nThe 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`:\n\n```\nkubectl --context tenant get secret kubernetes-fraud-admin-kubeconfig \\\n  -o jsonpath='{.data.admin\\.conf}' | base64 -d > ~/fraud-env/fraud.kubeconfig\nKUBECONFIG=~/fraud-env/fraud.kubeconfig kubectl config rename-context \\\n  \"$(KUBECONFIG=~/fraud-env/fraud.kubeconfig kubectl config current-context)\" fraud\nexport KUBECONFIG=~/.kube/config:~/fraud-env/fraud.kubeconfig\nkubectl --context fraud get nodes\n```\n\nYou 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.\n\nTwo 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.\n\n```\nkubectl --context fraud apply -f ~/fraud-env/terminals.yaml -f ~/fraud-env/prepull.yaml\n```\n\nOur imaginary terminals start sending payments right away: the switch is already running and, for now, approves everything.\n\nIn 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.\n\n```\ngit clone https://<your-git>/<you>/fraud-infra.git ~/fraud-infra\nmkdir -p ~/fraud-infra/platform\ncp ~/fraud-env/cluster.yaml ~/fraud-infra/platform/kubernetes.yaml\ncp ~/fraud-env/switch-vm.yaml ~/fraud-infra/platform/switch-vm.yaml\ncd ~/fraud-infra && git add platform && git commit -m \"Initial infrastructure\" && git push\n```\n\nTo 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.\n\n```\nkubectl --context tenant create secret generic git-flux --from-literal=username=<login> --from-literal=password=<token>\nkubectl --context tenant apply -f - <<EOF\napiVersion: source.toolkit.fluxcd.io/v1\nkind: GitRepository\nmetadata: {name: infra}\nspec:\n  interval: 1m\n  url: https://<your-git>/<you>/fraud-infra.git\n  ref: {branch: main}\n  secretRef: {name: git-flux}\n---\napiVersion: kustomize.toolkit.fluxcd.io/v1\nkind: Kustomization\nmetadata: {name: platform}\nspec:\n  interval: 1m\n  sourceRef: {kind: GitRepository, name: infra}\n  path: ./platform\n  prune: false\n  targetNamespace: $T\n  serviceAccountName: $T\nEOF\nkubectl --context tenant get kustomization platform\n```\n\nWhen `platform` shows `READY True`, everything is wired up: once a minute Flux pulls the latest `main` and applies the `platform/` folder.\n\nThe 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.\n\nAfter setup we have two kubectl contexts:\n\n``` bash\n$ kubectl config get-contexts\nCURRENT   NAME     CLUSTER    AUTHINFO      NAMESPACE\n          fraud    fraud      fraud-admin   fraud\n*         tenant   platform   austin03      tenant-austin03\n```\n\nThrough 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:\n\n``` bash\n$ kubectl --context tenant get vminstances,kubernetes\nNAME     READY   AGE   VERSION\nswitch   True    26m   f379a04795e8\n\nNAME    READY   AGE   VERSION\nfraud   True    26m   7c18a8ec4e4d\n\n$ kubectl --context tenant get resourcequota\nNAME           REQUEST                                                         LIMIT                                                 AGE\ntenant-quota   requests.cpu: 4525m/16, ...                                     limits.cpu: 30258m/160, limits.memory: 42104Mi/96Gi    29m\n\n$ kubectl --context fraud -n fraud get pods\nNAME                        READY   STATUS      RESTARTS   AGE\nprepull-explainer-2s24n     0/1     Completed   0          23m\nterminals-7cf5b9b59-6hfzv   1/1     Running     0          23m\n```\n\nThe 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.\n\nNow 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:\n\n``` bash\n$ journalctl -u auth-switch --no-pager -n 3\nNov 23 03:28:34 switch auth-switch[650]: 5s: 100 authorizations, 0 declined, stand-in 0.0%, p99 0 ms\nNov 23 03:28:39 switch auth-switch[650]: 5s: 100 authorizations, 0 declined, stand-in 0.0%, p99 0 ms\n```\n\nIn 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.\n\n*Looking around: both contexts, the switch and the cluster are in place, and payments are already flowing*\n\nNow 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.\n\n``` bash\n$ kubectl --context fraud apply -f manifests/04-attack.yaml\njob.batch/attack created\n\n$ kubectl --context fraud -n fraud logs job/attack --tail=4\nattack: impossible travel on card …4653 from Charlotte\nattack: impossible travel on card …5504 from Chicago\n5s: sent 30, approved 30, declined 0, errors 0, timeouts 0, p99 10.1 ms\n5s: sent 21, approved 21, declined 0, errors 0, timeouts 0, p99 10.1 ms\n```\n\nThe 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.\n\nIn the recording, keep an eye on the `approved` column: every single payment goes through.\n\n*An attack on a switch with no fraud check: every payment goes through*\n\nEverything 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.\n\nFrom 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.\n\nWe’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:\n\n```\n# platform/redis.yaml\napiVersion: apps.cozystack.io/v1alpha1\nkind: Redis\nmetadata:\n  name: features\nspec:\n  replicas: 1\n  size: 1Gi\n  storageClass: replicated\n  authEnabled: false\n```\n\nKafka and PostgreSQL we’ll write straight in YAML, following the documentation ([Kafka](https://cozystack.io/docs/v1.7/applications/kafka/), [PostgreSQL](https://cozystack.io/docs/v1.7/applications/postgres/)). In Cozystack 1.7, Kafka runs in KRaft mode without ZooKeeper, so the declaration only has the broker and the topics:\n\n```\n# platform/kafka.yaml\napiVersion: apps.cozystack.io/v1alpha1\nkind: Kafka\nmetadata:\n  name: kafka\nspec:\n  kafka:\n    replicas: 1\n    size: 5Gi\n    storageClass: replicated\n    resourcesPreset: c1.small\n  topics:\n    - {name: auth.requests, partitions: 8, replicas: 1, config: {}}\n    - {name: auth.decisions, partitions: 8, replicas: 1, config: {}}\n    - {name: auth.journal, partitions: 8, replicas: 1, config: {}}\n```\n\nNotice that the `auth.requests` topic has eight partitions. We’ll see why that matters in part four.\n\nIn 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.\n\n```\n# platform/postgres.yaml\napiVersion: apps.cozystack.io/v1alpha1\nkind: Postgres\nmetadata:\n  name: cases\nspec:\n  replicas: 2\n  size: 2Gi\n  storageClass: replicated\n  resourcesPreset: t1.micro\n  users:\n    fraud: {}\n  databases:\n    fraud:\n      roles:\n        admin: [fraud]\n```\n\nAdd the files to the repository, push them to `main` and watch what happens on the platform:\n\n``` bash\n$ kubectl --context tenant get kafka,redis,postgres\nNAME    READY     AGE   VERSION\nkafka   Unknown   42s   744a68a3a447\n\nNAME       READY   AGE   VERSION\nfeatures   True    42s   a0db0b4ba6d4\n\nNAME    READY     AGE   VERSION\ncases   Unknown   42s   ebc4944b1a9e\n```\n\n*Ordering services through Git: push, and a minute later the resources start coming up*\n\nRedis 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:\n\n``` bash\n$ kubectl --context tenant get hr\nNAME                 AGE   READY   STATUS\nkafka-kafka          6m    True    ...\nkubernetes-fraud     ...\npostgres-cases       ...\n\n$ kubectl --context tenant get pods -l cnpg.io/cluster=postgres-cases -L role\nNAME                            READY   STATUS      RESTARTS   AGE     ROLE\npostgres-cases-1                1/1     Running     0          119s    primary\npostgres-cases-1-initdb-kx66m   0/1     Completed   0          2m24s\npostgres-cases-2-join-lkqts     1/1     Running     0          98s\n```\n\nNow 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:\n\n``` bash\n$ kubectl --context tenant delete redis features\nredis.apps.cozystack.io \"features\" deleted\n\n$ kubectl --context tenant get redis -w\nNAME       READY     AGE    VERSION\n           Unknown   292y   <unknown>     <-- the object is deleted\nfeatures   Unknown   0s     <unknown>     <-- ...and immediately created again\nfeatures   True      56s    a0db0b4ba6d4\n```\n\nAbout 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.\n\n*Redis deleted by hand comes back in about a minute*\n\nWith 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.\n\nFirst, 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:\n\n```\nkubectl --context fraud -n fraud create secret generic cases-db \\\n  --from-literal=password=\"$(kubectl --context tenant get secret postgres-cases-credentials -o jsonpath='{.data.fraud}' | base64 -d)\"\n```\n\nNow we can deploy the applications:\n\n``` bash\n$ kubectl --context fraud apply -f manifests/02-scoring.yaml\ndeployment.apps/scorer created\ndeployment.apps/cases created\ndeployment.apps/dashboard created\nservice/dashboard created\n```\n\nThe 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:\n\n```\nsudo sed -i 's#^KAFKA_BOOTSTRAP=.*#KAFKA_BOOTSTRAP=kafka-kafka-kafka-bootstrap:9092#' /etc/auth-switch/env\nsudo systemctl restart auth-switch\njournalctl -u auth-switch --no-pager -n 3\n```\n\nThe 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.\n\n```\nswitch started in SCORING mode\nHTTP listening on :8080\n5s: 111 authorizations, 0 declined, stand-in 0.0%, p99 272 ms\n```\n\n`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.\n\n``` bash\n$ curl -s https://fraud.austin03.workshop.aenix.io/metrics | grep \"^fraud_\" | head -12\nfraud_authorizations_per_second 9.7        # still ramping up to ~20\nfraud_declines_per_second 0.3\nfraud_stand_in_ratio 0\nfraud_decision_latency_p50_seconds 0.0117  # ~12 milliseconds per decision\nfraud_transactions_stored 582\nfraud_alerts_total 18\nfraud_scorer_lag_messages 8\nfraud_cases_lag_messages 6\nfraud_journal_entries 588\nfraud_journal_missing 6\n```\n\nThe 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.\n\n*Turning the check on: the switch moves to Kafka, decisions take about 12 ms*\n\nNow 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.\n\nAll 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:\n\n``` bash\n$ kubectl --context fraud apply -f manifests/03-explainer.yaml\n$ kubectl --context fraud -n fraud rollout status deploy/explainer --timeout=5m\ndeployment \"explainer\" successfully rolled out\n```\n\nThe 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:\n\n``` bash\n$ kubectl --context fraud apply -f manifests/04-attack.yaml\njob.batch/attack created\n\n$ kubectl --context fraud -n fraud logs job/attack -f\nattack: card testing on card …1176: 36 probes of $0.50–$3.00\nattack: impossible travel on card …4653 from Charlotte\n...\n5s: sent 30, approved 24, declined 6, errors 0, timeouts 0, p99 125.0 ms\n5s: sent 21, approved 6, declined 6, errors 0, timeouts 0, p99 125.0 ms\n5s: sent 12, approved 0, declined 6, errors 0, timeouts 0, p99 125.0 ms\n```\n\nThe 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.\n\nThe rules the scorer uses live in a short Go file, [`rules.go`](https://github.com/aenix-org/cozystack-workshop/blob/master/fraud/app/internal/scoring/rules.go). If you want to change the thresholds, start there, not in the YAML.\n\nThe same attack that sailed through in part zero is now declined after the first few attempts:\n\n*The repeated attack: the first attempts get through, then fraudulent payments are declined*\n\nThe 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:\n\n```\n# platform/clickhouse.yaml\napiVersion: apps.cozystack.io/v1alpha1\nkind: ClickHouse\nmetadata:\n  name: analytics\nspec:\n  replicas: 1\n  shards: 1\n  resourcesPreset: t1.medium\n  size: 5Gi\n  storageClass: replicated\n  clickhouseKeeper:\n    enabled: false\n  users:\n    fraud:\n      password: Fraud2026\n```\n\nClickHouse 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:\n\n``` bash\n$ kubectl --context tenant exec -it chi-clickhouse-analytics-clickhouse-0-0-0 -c clickhouse -- \\\n    clickhouse-client --user fraud --password Fraud2026\n```\n\nThe 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-`.\n\nClickHouse 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:\n\n```\nCREATE TABLE journal_stream (raw String) ENGINE = Kafka\nSETTINGS kafka_broker_list = 'kafka-kafka-kafka-bootstrap:9092',\n         kafka_topic_list = 'auth.journal', kafka_group_name = 'clickhouse-analytics',\n         kafka_format = 'JSONAsString', kafka_max_block_size = 1000, kafka_poll_max_batch_size = 1000;\n\nCREATE TABLE payments (...) ENGINE = MergeTree ...;\n\nCREATE MATERIALIZED VIEW payments_stream_mv TO payments\nAS SELECT ... FROM journal_stream;\n```\n\nThe easiest way to load the file is with the same client, on standard input:\n\n```\nkubectl --context tenant exec -i chi-clickhouse-analytics-clickhouse-0-0-0 -c clickhouse -- \\\n  clickhouse-client --user fraud --password Fraud2026 --multiquery < manifests/05-analytics.sql\n```\n\nA couple of minutes later the `payments` table is answering queries and holds everything the switch has seen since the check was turned on:\n\n``` bash\n$ clickhouse-client ... -q \"SELECT count(*) AS stored_payments FROM payments\"\n329860   -- the journal has been growing since the check was turned on, so your number will differ\n\n$ clickhouse-client ... -q \"SELECT merchant, count(*) AS declines FROM payments\n    WHERE decision = 'DECLINE' GROUP BY merchant ORDER BY declines DESC LIMIT 10\"\n```\n\n*ClickHouse reads Kafka directly: stored payments and the merchants with the most declines*\n\nThe 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.\n\nThe 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`.\n\n```\n# platform/bucket.yaml\napiVersion: apps.cozystack.io/v1alpha1\nkind: Bucket\nmetadata:\n  name: reports\nspec:\n  users:\n    analytics: {}\n```\n\nA 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:\n\n```\nINSERT INTO FUNCTION s3('https://s3.workshop.aenix.io/<bucket>/daily-report.csv',\n                        '<accessKey>', '<secretKey>', 'CSVWithNames')\nSETTINGS s3_truncate_on_insert=1\nSELECT merchant, count(*) AS declines FROM payments\nWHERE decision = 'DECLINE' GROUP BY merchant ORDER BY declines DESC LIMIT 10;\nbash\n$ clickhouse-client ... -q \"SELECT count(*) FROM s3('...daily-report.csv', ...)\"\n10\n```\n\nThe recording shows the report being exported to the bucket and the check that it arrived:\n\n*Exporting a report from ClickHouse to S3 with a single INSERT, then checking it*\n\nYou can also open the report in a browser, in the object storage UI, which uses the same login as the Cozystack dashboard. Getting from a stream of payments in Kafka to a finished CSV file took one SQL file and not a single service of our own.\n\nIn the last part we put the system through the worst day a bank can have. There are three trials, and they come almost back to back.\n\nFirst, the autoscaling. It’s an ordinary `HorizontalPodAutoscaler` that targets an average of 250 millicores of CPU per pod and scales the scorer between one and eight replicas:\n\n```\napiVersion: autoscaling/v2\nkind: HorizontalPodAutoscaler\nmetadata:\n  name: scorer\n  namespace: fraud\nspec:\n  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: scorer}\n  minReplicas: 1\n  maxReplicas: 8\n  metrics:\n    - type: Resource\n      resource:\n        name: cpu\n        target: {type: AverageValue, averageValue: 250m}\n```\n\nThis object belongs to our own cluster, not to the platform, so we save it as `hpa.yaml` and apply it through the `fraud` context. The terminals read their traffic rate from a ConfigMap, and you can raise it without a restart: Kubernetes passes the new value to the pod within a minute.\n\n``` bash\n$ kubectl --context fraud -n fraud patch configmap traffic -p '{\"data\":{\"rate\":\"200\"}}'\nconfigmap/traffic patched\n```\n\nFor the next few minutes, keep an eye on both the autoscaler and the dashboard:\n\n``` bash\n$ kubectl --context fraud -n fraud get hpa scorer -w\nscorer   Deployment/scorer   cpu: 182m/250m   1   8   1   15s\nscorer   Deployment/scorer   cpu: 476m/250m   1   8   1   105s\nscorer   Deployment/scorer   cpu: 491m/250m   1   8   2   2m\nscorer   Deployment/scorer   cpu: 468m/250m   1   8   4   2m30s\n```\n\nA single scorer replica cannot handle ten times the traffic. Its CPU use goes far past the 250 millicore target, answers stop fitting into 400 milliseconds, and the switch starts deciding on its own. At that moment the dashboard shows 148 authorizations per second, 95% of them handled by the switch in stand-in mode. Decision latency hits the same 400 milliseconds, and the scorer’s queue grows to fifteen hundred messages. In a real bank, these are the minutes when fraudulent payments go through unchecked.\n\nThen the autoscaler kicks in. A minute and a half later two scorer replicas are running, two and a half minutes later four, and the queue is gone before you’ve worked out what’s going on. If you pin the replica count at 12 (set both `minReplicas` and `maxReplicas` to 12), you will find that only eight replicas actually work, and the other four report `scored 0`. The reason is that the `auth.requests` topic has eight partitions, and within one Kafka consumer group each partition is read by only one consumer at a time. The scaling limit was set when the topic was created, and adding pods won’t get around it. It is like a supermarket with eight checkouts: calling in a ninth cashier won’t make the line move any faster, because there is no free till for them.\n\nWhen we bring the rate back to normal, `rate: 20`, the autoscaler scales the scorer back down to one replica on its own within about five minutes.\n\n*Black Friday: CPU goes past 250m, and the scorer grows from one replica to two, then four*\n\nThe second trial is the kind of failure you prepare for in advance: the server running the PostgreSQL primary goes down. CloudNativePG keeps a hot replica for us. Let’s find the primary and delete its pod, as if the server had suddenly lost power. The `--grace-period=5` flag cuts the time for a clean shutdown to five seconds:\n\n``` bash\n$ kubectl --context tenant get pods -l cnpg.io/cluster=postgres-cases -L role\npostgres-cases-1   1/1   Running   0   5h   primary\npostgres-cases-2   1/1   Running   0   5h   replica\n\n$ kubectl --context tenant delete pod postgres-cases-1 --grace-period=5\npod \"postgres-cases-1\" deleted\n\n$ kubectl --context tenant get pods -l cnpg.io/cluster=postgres-cases -L role -w\npostgres-cases-2   1/1   Running      0   5h   primary        <-- a few seconds later\npostgres-cases-1   0/1   Init:0/1     0   1s\npostgres-cases-1   1/1   Running      0   27s   replica       <-- back as a replica\n```\n\nThe switch-over took a few seconds. The operator promoted the replica to primary, and the deleted pod came back as a replica of the new primary. So what did this do to payments? For a few seconds the dashboard showed the database as unavailable and the queue of entries waiting for the database grew a little, but that was all. The switch never talks to the database directly, and its journal waited calmly in Kafka the whole time. In the `cases` log it looks like this:\n\n```\ndatabase unavailable, holding 140 messages, retrying\n```\n\nAs soon as the database was available again, `cases` wrote all the pending messages into it. The reconciliation line on the dashboard compares the number of entries the switch wrote with the number of rows in the database, and within a minute it was back to `missing: 0`. Not a single entry was lost, because our main source of truth is the journal in Kafka, and the database simply catches up with it.\n\n*Losing the PostgreSQL primary: the replica takes over in seconds and pending entries are written to the database*\n\nBanks usually run the last trial at night, during a maintenance window. The server the switch runs on needs maintenance, so we ask the platform to move the running virtual machine to another node:\n\n``` bash\n$ kubectl --context tenant get vmi vm-instance-switch -o wide\nvm-instance-switch   Running   10.244.44.136   ws3   ...\n\n$ virtctl migrate vm-instance-switch\nVM vm-instance-switch was scheduled to migrate\n\n$ kubectl --context tenant get vmim -w\nkubevirt-migrate-vm-bz5dk   Scheduling\nkubevirt-migrate-vm-bz5dk   Scheduled\nkubevirt-migrate-vm-bz5dk   PreparingTarget\nkubevirt-migrate-vm-bz5dk   TargetReady\nkubevirt-migrate-vm-bz5dk   Running\nkubevirt-migrate-vm-bz5dk   Succeeded          <-- in under a minute\n\n$ kubectl --context tenant get vmi vm-instance-switch -o wide\nvm-instance-switch   Running   10.244.44.136   ws1   ...\n```\n\nWhile the machine keeps running, its memory is copied to the new server. The disk does not need to move, because it sits on replicated storage that both servers can reach. The VM’s address stays the same, the switch does not restart, and the terminals keep sending payments before, during and after the move. The price of the move is a couple of seconds while the VM’s network is set up on the new server. During those seconds a few authorizations go unanswered, and the terminals resend them with the same transaction ID, just as real store terminals do. The dashboard shows these payments under Repeated by the terminal, and Terminal errors stays at zero the whole time.\n\nYou can go two ways from here. You can change the thresholds and weights in [`rules.go`](https://github.com/aenix-org/cozystack-workshop/blob/master/fraud/app/internal/scoring/rules.go), rebuild the image and see how the system handles the same attack. Or you can work through the rest of the [cozystack-workshop](https://github.com/aenix-org/cozystack-workshop) repository: [sixteen labs](https://github.com/aenix-org/cozystack-workshop/tree/master/en/laptop/labs), from your own cluster from the catalog to OpenBao and live migration of virtual machines, and the [VMware migration workshop](https://github.com/aenix-org/cozystack-workshop/tree/master/en/laptop), built the same way.", "url": "https://wpnews.pro/news/build-your-own-fraud-detection-on-cozystack-a-legacy-card-switch-gitops-an-llm", "canonical_source": "https://dev.to/tym83/build-your-own-fraud-detection-on-cozystack-a-legacy-card-switch-gitops-an-llm-and-managed-4f4i", "published_at": "2026-12-03 23:02:29+00:00", "updated_at": "2026-12-03 23:17:02.440143+00:00", "lang": "en", "topics": ["ai-infrastructure", "large-language-models", "mlops", "ai-tools"], "entities": ["Cozystack", "Aenix", "Kafka", "Redis", "PostgreSQL", "CNCF", "aenix-org/cozystack-workshop"], "also_reported_by": [], "takeaway": "Cap the fraud scorer at a 400ms deadline and fall back to the switch's hard-coded logic, journal every decision regardless of who made it, and run the explanation LLM in-cluster so card data never leaves.", "recommendation": {"advice": "Set a hard timeout on the scoring service and fall back to deterministic switch logic, then reconcile the journal against the database to catch mismatches.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/build-your-own-fraud-detection-on-cozystack-a-legacy-card-switch-gitops-an-llm", "markdown": "https://wpnews.pro/news/build-your-own-fraud-detection-on-cozystack-a-legacy-card-switch-gitops-an-llm.md", "text": "https://wpnews.pro/news/build-your-own-fraud-detection-on-cozystack-a-legacy-card-switch-gitops-an-llm.txt", "jsonld": "https://wpnews.pro/news/build-your-own-fraud-detection-on-cozystack-a-legacy-card-switch-gitops-an-llm.jsonld"}}