ActualBuild Start a project

Writing / Engineering breakdown · Case study summary

How I built NotLogs: a logging platform on NATS, ClickHouse and AWS

01In one minute

WhatA log ingestion, search and alerting platform for developers
My partDesigned and built end to end: SDK, API, dashboard, billing, AWS infra, CI/CD
StackNestJS, Next.js, NATS, ClickHouse, Redis, Postgres, AWS, Terraform
  • Core idea: put a durable queue between the API and the database, so customer apps never wait on storage.
  • Hardest parts: ClickHouse write batching, a sort key that keeps queries fast per customer, and alerts that do not fire twice when containers scale.
  • Honest gaps: ClickHouse and NATS run on one EC2 box, retention is one global 30-day setting for every plan, and I have not published production benchmarks yet.

02The problem

Most logging tools assume you have a platform team. A solo developer or a small startup just wants to send logs, search them, and get a message when something breaks. Instead they get agents to install, YAML to maintain, and per-host billing that is hard to predict.

NotLogs is my attempt at the opposite: one SDK call to start, flat INR pricing, and an architecture that stays fast and cheap to run. Three constraints shaped everything:

  • Customer apps must never slow down because of us. Ingestion has to be quick no matter what the database is doing.
  • Search must stay fast as data grows, and every query is scoped to one customer.
  • Running cost must stay small. The whole production stack is roughly $155 to $170 per month by my Terraform estimate.
The NotLogs landing page
The NotLogs landing page

03The product

A developer signs in, creates an API key, installs the SDK and sees logs arrive. Three screens carry most of the work.

Overview: volume and error charts, top sources, and system health
Overview: volume and error charts, top sources, and system health
API keys: only a prefix is shown, keys can be revoked instantly (prefixes blurred here)
API keys: only a prefix is shown, keys can be revoked instantly (prefixes blurred here)

Alerts, a query explorer with filters like level:error service:billing, and a billing page with Razorpay checkout sit in the same console.

04Architecture in 60 seconds

AWS ap-south-1Your appSDK batches logsCloudFront + WAFrate limit at edgeALBHTTPS routingNestJS APIECS FargateNATS JetStreamdurable queueWorkerqueue consumerClickHouselog storageRediskeys, quotas, countersPostgres (Neon)users, plans, rulesinsert123456
Write path. Numbers match the walkthrough below. Grey lines are reads and counters, not the main path.
  1. SDK to edge. The SDK batches logs and posts them over HTTPS. WAF rejects abusive IPs before they reach any server.
  2. ALB to API. The load balancer routes to the NestJS API running on ECS Fargate.
  3. API publishes. The API checks the key and quota, publishes the batch to NATS, and returns 200.
  4. NATS holds it. JetStream stores the message on disk until a worker takes it.
  5. Worker processes. It inserts into ClickHouse, bumps usage counters and feeds live tail and alerts.
  6. Supporting stores. Redis serves hot data (keys, quotas, counters). Postgres is the source of truth for accounts, plans and payments.

This split, a fast stateless front and a durable queue in the middle, is what the rest of the post unpacks.

05Follow one log

The best way to see the pieces fit is to follow a single line from code to screen.

logger.error('payment timeout', { orderId: 42 })
  1. SDK: the line goes into an in-memory buffer. It flushes at 100 logs or after 2 seconds.
  2. Request: the batch is sent with the API key to POST /api/v1/logs/send. WAF and ALB let it through.
  3. Guards: the key is verified (memory, then Redis, then Postgres) and the account quota is checked.
  4. Queue: the API publishes to logs.ingest and answers 200. The customer app is free.
  5. Worker: inserts into ClickHouse, adds to the usage counter in Redis, and forwards the event to alert evaluation and live tail.
  6. Alert: if a rule says 5 errors in 5 minutes, a signed webhook goes to Discord or Slack.
  7. Search: later you type level:error search:timeout and ClickHouse answers from the stored rows.

06Ingestion: accept now, write later

The tempting design is to have the API insert each batch straight into the database. The problem is coupling: a slow insert or a ClickHouse restart becomes a slow or failed response for every customer app. With a queue in the middle, the API does three cheap checks and hands the batch to NATS.

// publish, then respond
await js.publish('logs.ingest', jc.encode({ keyId, userId, logs, serverReceivedAt }));

Why NATS JetStream and not the usual suspects:

OptionGood atWhy not here
KafkaHuge scale, replayBrokers and a controller quorum to operate; too heavy for a small team
AWS SQSZero opsPer-request cost and weaker fit for high-rate batches
NATS JetStreamOne small binary, file-backed durable streams, queue groupsSingle node today, so no HA yet (see the end)

Workers are a queue group (sel-log-worker-group), so adding workers spreads the load automatically.

A mistake that taught me something

My first worker inserted every log with its own INSERT. Under load test, ClickHouse threw too many parts errors, because each insert creates a data part it must later merge. The fix was to let ClickHouse batch for me:

clickhouse_settings: {
  async_insert: 1,
  wait_for_async_insert: 0,
  async_insert_max_data_size: '10485760', // flush at 10 MB
  async_insert_busy_timeout_ms: '500',    // or after 500 ms
}

07Storage: ClickHouse and one important line

Logs are written once, never updated, and read by time range and filters. That is the textbook case for a columnar database, and a poor fit for Postgres at scale or a heavy search cluster. I chose ClickHouse for three reasons: it compresses repetitive log data well, scans only the columns a query needs, and handles retention as a table setting.

CREATE TABLE logs.events (...)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(timestamp)
ORDER BY (userId, keyId, appName, timestamp)
TTL timestamp + INTERVAL 30 DAY DELETE
  • ORDER BY decides speed. Data is stored sorted by that key and a sparse index points into it. My first key started with timestamp, which meant a customer's query still had to touch every time block. Putting userId first lets ClickHouse jump straight to that customer's rows.
  • Partition by month, TTL 30 days. Old data expires on its own with no cleanup job. This is one global setting for now.
  • LowCardinality columns for fields like type, app name and environment, which have few distinct values and compress very well.
  • Query box. The API parses tokens like level:error service:billing search:timeout range:24h into SQL, with a 2-second cooldown per user to stop dashboard spam.

Live tail

The API has a Server-Sent Events endpoint. On connect it sends recent events from ClickHouse (the dashboard asks for 50) so the screen is never empty, then keeps an in-memory registry of connections with their filters and pushes matching new logs in chunks of 50. The dashboard's Live Logs page itself currently polls every 4 seconds; moving it onto the stream is on my list.

Live Logs page loading recent logs from the API, refreshed every 4 seconds
Live Logs page loading recent logs from the API, refreshed every 4 seconds

08API keys and security

Keys look like SEL_<id>_<secret>. Only the Argon2id hash is stored (64 MB memory cost, 3 passes). Argon2 is deliberately slow, which is great against theft and terrible on a hot path that sees every log batch. So verification goes through cheap tiers first:

Memory LRU100k keys, in-processRedis hash24h cachePostgres + Argon2idslow, source of truthmissmissAllowedAllowedAllowed + cache ithithitvalidRejected 401invalidInvalid keys are cached 24hso floods never reach Argon2.
Each tier runs only if the one before it misses.
  • Negative caching is the part I like most. Without it, anyone could send random keys and force the server to run Argon2 each time, which is a CPU denial of service.
  • Fail open on quota checks. If Redis or Postgres has a blip, UsageGuard falls back to free-tier limits instead of returning 500s. Dropping customer logs because my quota lookup failed would be worse than a brief limit mismatch.
  • Edge rate limit. WAF allows 1,000 requests per 5 minutes per IP on the ingestion path, so floods die before reaching Node.

09Alerts without polling

A rule says something like "5 errors in 5 minutes, then notify Discord". Polling ClickHouse every few seconds for every rule would not scale, so the check happens in-stream: workers publish each event to an alert subject, and a consumer increments a time-bucketed counter in Redis.

Workersees every loglogs.alert.evaluateNATS subjectQueue group: oml-alert-worker-groupAPI container Aalert consumerAPI container Balert consumereach event goesto ONE of themRediswindow count + cooldownWebhookHMAC-SHA256 signedRedis DLQafter 3 failed tries
Alert path. Counting happens in Redis, ClickHouse is never polled.
  • Counters are keyed oml:alert:count:{rule}:{bucket} and expire on their own. A separate cooldown key stops repeat notifications.
  • Signed webhooks. Each request carries x-oml-signature: sha256=..., an HMAC the receiver can verify.
  • Retries. Three attempts at 1s, 2s and 4s. After that the notification goes to a capped dead-letter list so nothing vanishes silently.

10Billing and quotas

Each user has a monthly event limit tracked in Redis with atomic increments. When usage reaches the limit, a lock key is set and ingestion returns 403 until the plan changes.

Upgrades use Razorpay checkout. The important part is what happens after payment, because the user expects to be unblocked instantly:

  1. Server verifies the Razorpay HMAC signature.
  2. Postgres records the payment and new plan.
  3. Redis plan limits are updated and the lock key deleted.
  4. In-memory caches are purged. No restart, no waiting.

11The SDK

The Node SDK has no dependencies and is built around one rule: never lose logs and never block the app.

  • Two flush triggers: 100 buffered logs, or 2 seconds of idle time, whichever comes first.
  • Atomic swap: buffers.splice(0, buffers.length) takes the whole batch in one step, so logs written during a flush are not lost or duplicated.
  • Graceful shutdown: hooks on SIGINT, SIGTERM and beforeExit flush before a container dies.
Docs with a quick start and Express/NestJS guides
Docs with a quick start and Express/NestJS guides

Wrappers exist for NestJS, React and Next.js.

12AWS infrastructure

UsersCloudFront + WAFv2VPC, public subnets (2 AZ)ALBNAT GatewayPrivate subnets (2 AZ)ECS FargateARM64: API, webEC2 + EBSClickHouse, NATSElastiCacheRedis 7via NATNeon PostgresexternalAll provisioned with Terraform.
Where everything runs. Stateless apps on Fargate, stateful engines on one EC2 box.
PieceRole
CloudFront + WAFv2Caches static assets, rate limits at the edge
ALBTLS, HTTP to HTTPS redirect, host and path routing
ECS Fargate (ARM64)NestJS API, Next.js dashboard, marketing site
EC2 + encrypted EBSClickHouse and NATS, the two stateful engines
ElastiCache Redis 7Key cache, usage meters, alert counters
Neon PostgresAccounts, plans, payments, alert rules

Honest trade-off: ClickHouse and NATS share one small EC2 instance. That keeps cost low but it is a single point of failure, and it is the first thing I would harden.

13Deploys

1. Push to main2. Detect change3. Build ARM644. Push to ECR5. ECS deploy6. Health checksAuto rollbackLivefailpass
Only the app that changed is rebuilt. Failed health checks trigger rollback with no human involved.

Path filters decide which app changed, so a landing page tweak does not rebuild the API. Images are built on native ARM64 GitHub runners with layer caching, which avoids slow emulation. ECS uses a deployment circuit breaker, so a bad release rolls back on its own.

14Key decisions and their cost

Every choice below has a price. These are the ones I would want to discuss.

DecisionWhyWhat it costs
Queue between API and databaseCustomer apps never wait on storageOne more moving part; logs appear after a short delay
ClickHouse for logsFast scans, built-in retention, cheap to runWeaker free-text search than Elasticsearch
NATS JetStream, not KafkaSmall, durable, easy to runSingle node today, no HA yet
Rate limit at WAFFloods rejected before they reach NodeCoarse per-IP rule
Argon2id keys with 3 cache tiersSafe storage with a fast hot pathMore layers to keep consistent
Terraform on FargateRepeatable infra, no servers to patchNAT gateway is a real monthly cost

15Mistakes and lessons

Duplicate alerts

Symptom. Customers got two Slack messages per alert.

Cause. ECS ran two containers and a plain subscription delivers every event to every subscriber.

Fix. Use a JetStream queue group (deliverGroup) so each event goes to one container.

Too many parts

Symptom. ClickHouse errors under load.

Cause. One INSERT per log creates too many tiny parts.

Fix. async_insert with a 10 MB / 500 ms buffer.

Payment modal loop

Symptom. Razorpay popup kept reopening and a build failed.

Cause. useSearchParams needs a Suspense boundary, and re-renders retriggered the checkout.

Fix. Wrap in Suspense and guard the auto-trigger with a useRef flag.

  • Put the tenant first in a multi-tenant ClickHouse sort key.
  • Keep slow crypto off the hot path, and cache failures too.
  • A monitoring or quota failure should degrade gracefully, not take ingestion down.

16What is next

  • Per-plan retention. The pricing page lists 7 to 180 days, but ClickHouse has one global 30-day TTL today. Plan-based retention is the next change.
  • Cold storage. Logs are deleted after 30 days. Tier older data to S3 instead.
  • Remove the single point of failure for ClickHouse and NATS.
  • Autoscaling. Task counts are fixed today; add CPU and memory target tracking.
  • OpenTelemetry endpoint, so teams can send logs without my SDK.
  • Published benchmarks. I have k6 load tests (thresholds like p95 under 500ms for ingestion), but I have not published production results yet, so this post makes no throughput claims.
Flat INR pricing: Free, Starter, Pro, Business
Flat INR pricing: Free, Starter, Pro, Business
LayerTech
APINestJS 11
WebNext.js 16, React 19, Tailwind 4
QueueNATS 2.10 JetStream
Analytics DBClickHouse
Relational DBNeon Postgres, Drizzle ORM
CacheElastiCache Redis 7, lru-cache
AuthClerk, Argon2id
PaymentsRazorpay
InfraAWS, Terraform
CI/CDGitHub Actions

17What this project shows

AreaWhere it shows up
Backend and APIsNestJS guards, batching SDK, signed webhooks
Distributed systemsDurable queue, consumer groups, retries, dead-letter list
DatabasesClickHouse sort key and TTL, Postgres with Drizzle, Redis counters
SecurityArgon2id, negative caching, HMAC signatures, WAF rules
Cloud and DevOpsTerraform, ECS Fargate, ALB, CI/CD with automatic rollback
Product and frontendNext.js dashboard, Clerk auth, Razorpay billing, docs site

Happy to go deeper on any of these. Code and contact: GitHub and LinkedIn.