<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://raghavendrapara.github.io/rc-says/feed.xml" rel="self" type="application/atom+xml" /><link href="https://raghavendrapara.github.io/rc-says/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-11-27T16:34:08+05:30</updated><id>https://raghavendrapara.github.io/rc-says/feed.xml</id><title type="html">Raghavendra Singh Chauhan</title><subtitle>Software engineer specializing in backend engineering, distributed systems, and AI systems. Articles, research notes and work logs.</subtitle><author><name>Raghavendra Singh Chauhan</name><email>raghavendra.swe666@gmail.com</email></author><entry><title type="html">Contest Maker 150: a Go API that builds timed practice contests from the NeetCode 150</title><link href="https://raghavendrapara.github.io/rc-says/projects/contest-maker-150/" rel="alternate" type="text/html" title="Contest Maker 150: a Go API that builds timed practice contests from the NeetCode 150" /><published>2026-11-27T00:00:00+05:30</published><updated>2026-11-27T00:00:00+05:30</updated><id>https://raghavendrapara.github.io/rc-says/projects/contest-maker-150</id><content type="html" xml:base="https://raghavendrapara.github.io/rc-says/projects/contest-maker-150/"><![CDATA[<h2 id="the-problem">The problem</h2>

<p>I was working through the NeetCode 150 list and wanted something closer to a contest than a checklist: pick N problems I
have not solved yet, put them in a sensible difficulty order, start a clock, and record what I finished so the next
contest does not hand me the same problems again.</p>

<p>That is a small domain (users, problems, contests, solved records), which made it a good excuse to build a Go backend
the way I would build a Java service at work: clear layers, typed domain errors, auth, a real database, graceful
shutdown, and traces and metrics from day one. The React frontend is a thin client over the API.</p>

<h2 id="architecture">Architecture</h2>

<div class="diagram">
<svg viewBox="0 0 740 380" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Browser calls an nginx container serving the React build, which proxies /api to the Go API. The API reads and writes PostgreSQL, exports traces to Jaeger, and exposes /metrics which Prometheus scrapes; Grafana reads Prometheus.">
  <defs><marker id="contest-maker-150-a1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead" /></marker><marker id="contest-maker-150-a2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead-accent" /></marker></defs>
  <rect x="165" y="24" width="565" height="340" rx="10" class="dg-group" />
  <text x="182" y="46" class="dg-label">docker compose network</text>
  <rect x="20" y="160" width="120" height="56" rx="8" class="dg-box" />
  <text x="80" y="184" text-anchor="middle" class="dg-text">Browser</text>
  <text x="80" y="202" text-anchor="middle" class="dg-sub">React SPA</text>
  <rect x="190" y="160" width="150" height="56" rx="8" class="dg-box" />
  <text x="265" y="184" text-anchor="middle" class="dg-text">frontend</text>
  <text x="265" y="202" text-anchor="middle" class="dg-sub">nginx, proxies /api</text>
  <rect x="380" y="130" width="175" height="116" rx="8" class="dg-box-accent" />
  <text x="467" y="160" text-anchor="middle" class="dg-text">Go API (Gin)</text>
  <text x="467" y="182" text-anchor="middle" class="dg-sub">middleware → handler</text>
  <text x="467" y="200" text-anchor="middle" class="dg-sub">→ service → repository</text>
  <text x="467" y="222" text-anchor="middle" class="dg-sub">JWT, zap, OTel spans</text>
  <rect x="595" y="160" width="120" height="56" rx="8" class="dg-box" />
  <text x="655" y="184" text-anchor="middle" class="dg-text">PostgreSQL</text>
  <text x="655" y="202" text-anchor="middle" class="dg-sub">GORM AutoMigrate</text>
  <rect x="595" y="62" width="120" height="50" rx="8" class="dg-box" />
  <text x="655" y="83" text-anchor="middle" class="dg-text">Jaeger</text>
  <text x="655" y="100" text-anchor="middle" class="dg-sub">OTLP over HTTP</text>
  <rect x="380" y="292" width="175" height="50" rx="8" class="dg-box" />
  <text x="467" y="313" text-anchor="middle" class="dg-text">Prometheus</text>
  <text x="467" y="330" text-anchor="middle" class="dg-sub">scrapes /metrics</text>
  <rect x="190" y="292" width="150" height="50" rx="8" class="dg-box" />
  <text x="265" y="313" text-anchor="middle" class="dg-text">Grafana</text>
  <text x="265" y="330" text-anchor="middle" class="dg-sub">datasources only</text>
  <line x1="140" y1="188" x2="188" y2="188" class="dg-line-accent" marker-end="url(#contest-maker-150-a2)" />
  <line x1="340" y1="188" x2="378" y2="188" class="dg-line-accent" marker-end="url(#contest-maker-150-a2)" />
  <line x1="555" y1="188" x2="593" y2="188" class="dg-line-accent" marker-end="url(#contest-maker-150-a2)" />
  <line x1="555" y1="145" x2="593" y2="100" class="dg-line-dashed" marker-end="url(#contest-maker-150-a1)" />
  <line x1="467" y1="292" x2="467" y2="248" class="dg-line-dashed" marker-end="url(#contest-maker-150-a1)" />
  <line x1="340" y1="317" x2="378" y2="317" class="dg-line" marker-end="url(#contest-maker-150-a1)" />
</svg>
<p class="diagram-caption">Figure 1. The six Compose services. The solid path is a user request; dashed lines are trace export (see the config note under "What I'd do next") and metric scraping.</p>
</div>

<p>The backend follows a standard Go layout: <code class="language-plaintext highlighter-rouge">cmd/api/main.go</code> wires everything, and <code class="language-plaintext highlighter-rouge">internal/</code> holds <code class="language-plaintext highlighter-rouge">domain</code>,
<code class="language-plaintext highlighter-rouge">handler</code>, <code class="language-plaintext highlighter-rouge">service</code>, <code class="language-plaintext highlighter-rouge">repository</code>, <code class="language-plaintext highlighter-rouge">middleware</code>, <code class="language-plaintext highlighter-rouge">infrastructure</code> and <code class="language-plaintext highlighter-rouge">data</code>.</p>

<ul>
  <li><strong>domain</strong> holds the GORM models (<code class="language-plaintext highlighter-rouge">User</code>, <code class="language-plaintext highlighter-rouge">Problem</code>, <code class="language-plaintext highlighter-rouge">Contest</code>, <code class="language-plaintext highlighter-rouge">ContestProblem</code>, <code class="language-plaintext highlighter-rouge">Submission</code>), the repository
interfaces, request/response DTOs and a set of sentinel errors such as <code class="language-plaintext highlighter-rouge">ErrActiveContestExists</code> and
<code class="language-plaintext highlighter-rouge">ErrContestExpired</code>.</li>
  <li><strong>repository</strong> implements those interfaces with GORM against Postgres.</li>
  <li><strong>service</strong> holds the business rules: one active contest per user, problem selection, ownership checks, and
password hashing and JWT issuing.</li>
  <li><strong>handler</strong> binds and validates JSON with Gin’s <code class="language-plaintext highlighter-rouge">binding</code> tags and maps domain errors to HTTP status codes (409 for
an existing active contest, 403 for someone else’s contest, 400 for an expired one).</li>
  <li><strong>middleware</strong> runs on every request in this order: panic recovery, request logging with a request ID, CORS, an
OpenTelemetry server span, and HTTP metrics. A JWT middleware guards the <code class="language-plaintext highlighter-rouge">/users</code> and <code class="language-plaintext highlighter-rouge">/contests</code> groups.</li>
</ul>

<p>On startup the API loads config from environment variables, connects to Postgres with a sized connection pool, runs
<code class="language-plaintext highlighter-rouge">AutoMigrate</code>, and seeds the 150 problems from a JSON file compiled into the binary with <code class="language-plaintext highlighter-rouge">//go:embed</code>. The seeder skips
the insert if the table already has rows. The HTTP server starts in a goroutine, and <code class="language-plaintext highlighter-rouge">SIGINT</code>/<code class="language-plaintext highlighter-rouge">SIGTERM</code> trigger
<code class="language-plaintext highlighter-rouge">server.Shutdown</code> with a 30-second deadline, followed by a flush of the trace provider.</p>

<p>The React app (Vite, TypeScript, Zustand, React Query) has pages for signup, login, a dashboard, contest creation, the
active contest with a countdown timer, and history. Its Axios client queues requests during a token refresh.</p>

<h2 id="key-design-decisions">Key design decisions</h2>

<p><strong>A contest is a row with a start time and a duration, not a running timer.</strong> <code class="language-plaintext highlighter-rouge">Contest</code> stores <code class="language-plaintext highlighter-rouge">StartedAt</code> and
<code class="language-plaintext highlighter-rouge">DurationMinutes</code>; <code class="language-plaintext highlighter-rouge">IsExpired()</code> and the <code class="language-plaintext highlighter-rouge">time_remaining_seconds</code> in each response are computed from those. There is no
background job. An expired contest is flipped to <code class="language-plaintext highlighter-rouge">completed</code> lazily, the next time it is read or the user tries to
create a new one. The alternative was a scheduler or a goroutine per contest. That is more moving parts and does not
survive a restart. The cost is that the stored status can be stale until someone touches the contest.</p>

<p><strong>“Unsolved” is decided in SQL, not in Go.</strong> Solved problems live in a <code class="language-plaintext highlighter-rouge">submissions</code> table, and the repository excludes
them with a <code class="language-plaintext highlighter-rouge">NOT IN</code> subquery. The alternative was loading the user’s solved IDs and filtering in memory. With 150
problems either works, but the subquery keeps the rule in one place and still works if the table grows.</p>

<p><strong>Difficulty mix by contest size, with spill-over.</strong> <code class="language-plaintext highlighter-rouge">calculateDistribution</code> picks the Easy/Medium/Hard split from the
requested count (for example 30/40/30 for 6-10 problems, 25/50/25 above that) and forces at least one of each once the
count is 3 or more. If a bucket runs short, the shortfall rolls over into the next, harder bucket. The final list is
sorted by difficulty weight so the contest ramps up. A plain random sample would have been simpler, but it would not
give the Easy-to-Hard ordering I wanted.</p>

<p><strong>Fan-out queries per difficulty.</strong> Problem selection and the progress endpoint each run three queries, one per
difficulty, in goroutines and collect the results over a buffered channel. That is a deliberate exercise of the Go
fan-out/fan-in pattern. Against a local Postgres a single <code class="language-plaintext highlighter-rouge">GROUP BY</code> query would do the same job, and I did not measure
a difference either way.</p>

<p><strong>Small distroless image for the API.</strong> The backend Dockerfile is a two-stage build: <code class="language-plaintext highlighter-rouge">golang:1.25-alpine</code> compiles a
static binary (<code class="language-plaintext highlighter-rouge">CGO_ENABLED=0</code>, <code class="language-plaintext highlighter-rouge">-ldflags="-w -s"</code>), and the runtime image is
<code class="language-plaintext highlighter-rouge">gcr.io/distroless/static-debian12:nonroot</code> with only the binary, CA certificates and zoneinfo. The trade-off is that
there is no shell or <code class="language-plaintext highlighter-rouge">wget</code> in the image, which matters for the Compose health check (see below).</p>

<h2 id="inside-the-code">Inside the code</h2>

<p>The selection step fans out one repository call per difficulty and fans the results back in. The buffered channel
sized to the number of workers means no goroutine blocks on send, and a separate goroutine closes the channel once the
<code class="language-plaintext highlighter-rouge">WaitGroup</code> drains:</p>

<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">resultChan</span> <span class="o">:=</span> <span class="nb">make</span><span class="p">(</span><span class="k">chan</span> <span class="n">difficultyResult</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">difficulties</span><span class="p">))</span>
<span class="k">var</span> <span class="n">wg</span> <span class="n">sync</span><span class="o">.</span><span class="n">WaitGroup</span>
<span class="n">fetchProblems</span> <span class="o">:=</span> <span class="k">func</span><span class="p">(</span><span class="n">diff</span> <span class="n">domain</span><span class="o">.</span><span class="n">Difficulty</span><span class="p">)</span> <span class="p">{</span>
	<span class="k">defer</span> <span class="n">wg</span><span class="o">.</span><span class="n">Done</span><span class="p">()</span>
	<span class="n">problems</span><span class="p">,</span> <span class="n">err</span> <span class="o">:=</span> <span class="n">s</span><span class="o">.</span><span class="n">problemRepo</span><span class="o">.</span>
		<span class="n">FindUnsolvedByUserAndDifficulty</span><span class="p">(</span><span class="n">userID</span><span class="p">,</span> <span class="n">diff</span><span class="p">)</span>
	<span class="n">resultChan</span> <span class="o">&lt;-</span> <span class="n">difficultyResult</span><span class="p">{</span>
		<span class="n">difficulty</span><span class="o">:</span> <span class="n">diff</span><span class="p">,</span> <span class="n">problems</span><span class="o">:</span> <span class="n">problems</span><span class="p">,</span> <span class="n">err</span><span class="o">:</span> <span class="n">err</span><span class="p">,</span>
	<span class="p">}</span>
<span class="p">}</span>
<span class="k">for</span> <span class="n">_</span><span class="p">,</span> <span class="n">diff</span> <span class="o">:=</span> <span class="k">range</span> <span class="n">difficulties</span> <span class="p">{</span>
	<span class="n">wg</span><span class="o">.</span><span class="n">Add</span><span class="p">(</span><span class="m">1</span><span class="p">)</span>
	<span class="k">go</span> <span class="n">fetchProblems</span><span class="p">(</span><span class="n">diff</span><span class="p">)</span>
<span class="p">}</span>
<span class="k">go</span> <span class="k">func</span><span class="p">()</span> <span class="p">{</span>
	<span class="n">wg</span><span class="o">.</span><span class="n">Wait</span><span class="p">()</span>
	<span class="nb">close</span><span class="p">(</span><span class="n">resultChan</span><span class="p">)</span>
<span class="p">}()</span>
<span class="c">// … collect into problemsByDifficulty, then apply the distribution</span>
</code></pre></div></div>

<p>The shared <code class="language-plaintext highlighter-rouge">*rand.Rand</code> used for the partial Fisher-Yates shuffle is guarded by a <code class="language-plaintext highlighter-rouge">sync.Mutex</code>, because
<code class="language-plaintext highlighter-rouge">math/rand.Rand</code> is not safe for concurrent use and the service is a singleton shared by all request goroutines.</p>

<p>The “never repeat a solved problem” rule is one subquery in the repository:</p>

<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">solvedSubquery</span> <span class="o">:=</span> <span class="n">r</span><span class="o">.</span><span class="n">db</span><span class="o">.</span><span class="n">Model</span><span class="p">(</span><span class="o">&amp;</span><span class="n">domain</span><span class="o">.</span><span class="n">Submission</span><span class="p">{})</span><span class="o">.</span>
	<span class="n">Select</span><span class="p">(</span><span class="s">"problem_id"</span><span class="p">)</span><span class="o">.</span>
	<span class="n">Where</span><span class="p">(</span><span class="s">"user_id = ?"</span><span class="p">,</span> <span class="n">userID</span><span class="p">)</span>

<span class="n">result</span> <span class="o">:=</span> <span class="n">r</span><span class="o">.</span><span class="n">db</span><span class="o">.</span><span class="n">Where</span><span class="p">(</span><span class="s">"id NOT IN (?)"</span><span class="p">,</span> <span class="n">solvedSubquery</span><span class="p">)</span><span class="o">.</span>
	<span class="n">Where</span><span class="p">(</span><span class="s">"difficulty = ?"</span><span class="p">,</span> <span class="n">difficulty</span><span class="p">)</span><span class="o">.</span>
	<span class="n">Order</span><span class="p">(</span><span class="s">"RANDOM()"</span><span class="p">)</span><span class="o">.</span>
	<span class="n">Find</span><span class="p">(</span><span class="o">&amp;</span><span class="n">problems</span><span class="p">)</span>
</code></pre></div></div>

<p>Marking a problem complete inside an active, unexpired contest writes a <code class="language-plaintext highlighter-rouge">Submission</code> row (once per user and problem),
and that row is what this subquery reads the next time a contest is generated.</p>

<h2 id="running-it">Running it</h2>

<p>From the repository root:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cp</span> .env.example .env          <span class="c"># set POSTGRES_PASSWORD and JWT_SECRET</span>
docker-compose up <span class="nt">-d</span>
<span class="c"># frontend http://localhost:3000, API http://localhost:8080</span>
<span class="c"># Jaeger :16686, Prometheus :9090, Grafana :3001</span>
</code></pre></div></div>

<p>For local development the README runs the API with <code class="language-plaintext highlighter-rouge">go run cmd/api/main.go</code> (it expects a Postgres on localhost) and
the frontend with <code class="language-plaintext highlighter-rouge">npm install &amp;&amp; npm run dev</code>.</p>

<h2 id="what-id-do-next">What I’d do next</h2>

<ul>
  <li><strong>Tests.</strong> There are no Go or frontend tests yet. The domain logic (<code class="language-plaintext highlighter-rouge">calculateDistribution</code>, <code class="language-plaintext highlighter-rouge">IsExpired</code>, the
shortfall carry-over) is pure and easy to table-test. The services already depend on repository interfaces, so
in-memory fakes would cover the contest rules.</li>
  <li><strong>Fix the env-var mismatch in Compose.</strong> <code class="language-plaintext highlighter-rouge">docker-compose.yml</code> sets <code class="language-plaintext highlighter-rouge">SERVER_ENVIRONMENT</code>, <code class="language-plaintext highlighter-rouge">TELEMETRY_OTEL_ENDPOINT</code>
and <code class="language-plaintext highlighter-rouge">JWT_ACCESS_EXPIRY</code>, but <code class="language-plaintext highlighter-rouge">config.go</code> reads <code class="language-plaintext highlighter-rouge">ENVIRONMENT</code>, <code class="language-plaintext highlighter-rouge">OTEL_EXPORTER_OTLP_ENDPOINT</code> and
<code class="language-plaintext highlighter-rouge">JWT_ACCESS_EXPIRY_MINUTES</code>. Inside Compose the API falls back to its defaults, so the trace exporter points at an
<code class="language-plaintext highlighter-rouge">otel-collector</code> host that does not exist instead of Jaeger.</li>
  <li><strong>Health check in a distroless image.</strong> The Compose health check calls <code class="language-plaintext highlighter-rouge">wget</code>, which the distroless runtime does not
have. A <code class="language-plaintext highlighter-rouge">-healthcheck</code> flag on the binary, or a tiny probe binary, would fix it.</li>
  <li><strong>Propagate context into the database.</strong> Every repository has a <code class="language-plaintext highlighter-rouge">WithContext</code> method, but services never call it, so
GORM queries are not tied to request cancellation or to the trace. Adding the <code class="language-plaintext highlighter-rouge">otelgorm</code> plugin would give DB spans.</li>
  <li><strong>Make “one active contest” a database guarantee.</strong> The check is read-then-insert in the service, so two concurrent
requests can both pass it. A partial unique index on <code class="language-plaintext highlighter-rouge">contests(user_id) WHERE status = 'active'</code> would close that.
Contest creation and adding its problems also run as two writes with a compensating delete instead of one
transaction.</li>
  <li><strong>Finish the half-built pieces.</strong> <code class="language-plaintext highlighter-rouge">GET /users/me/progress</code> returns per-difficulty counts, but <code class="language-plaintext highlighter-rouge">topic_progress</code> and
<code class="language-plaintext highlighter-rouge">contest_stats</code> are never filled in. Several metric instruments (<code class="language-plaintext highlighter-rouge">contests.active</code>, <code class="language-plaintext highlighter-rouge">problems.solved</code>,
<code class="language-plaintext highlighter-rouge">db.query.duration</code>) are created but never recorded. Un-marking a problem does not remove its submission. Grafana has
datasources but no dashboards.</li>
  <li><strong>Versioned migrations.</strong> <code class="language-plaintext highlighter-rouge">AutoMigrate</code> is fine for a single developer; golang-migrate or Atlas would make schema
changes reviewable.</li>
</ul>

<h2 id="skills-this-shows">Skills this shows</h2>

<ul>
  <li><strong>Go service structure:</strong> <code class="language-plaintext highlighter-rouge">cmd/</code> plus <code class="language-plaintext highlighter-rouge">internal/</code> layering, interfaces in the domain package, constructor injection
wired in <code class="language-plaintext highlighter-rouge">main.go</code>, and sentinel errors mapped to HTTP codes in handlers.</li>
  <li><strong>API design:</strong> REST resources with sub-resource actions (<code class="language-plaintext highlighter-rouge">PATCH /contests/:id/problems/:problemId</code>,
<code class="language-plaintext highlighter-rouge">POST /contests/:id/complete</code>), request validation via binding tags, and ownership checks on every contest route.</li>
  <li><strong>Concurrency:</strong> fan-out/fan-in with <code class="language-plaintext highlighter-rouge">WaitGroup</code> and buffered channels, and a mutex around a non-thread-safe RNG.</li>
  <li><strong>Persistence:</strong> a Postgres model with a composite-key join table, a <code class="language-plaintext highlighter-rouge">text[]</code> column for topics, subqueries for
exclusion, connection-pool settings and an idempotent seed from an embedded file.</li>
  <li><strong>Auth:</strong> bcrypt password hashing, HS256 access and refresh tokens with a <code class="language-plaintext highlighter-rouge">type</code> claim so a refresh token cannot be
used as an access token, and a check on the signing method.</li>
  <li><strong>Operations:</strong> graceful shutdown, <code class="language-plaintext highlighter-rouge">/health</code> with a DB ping, structured zap logs with request IDs, OpenTelemetry
server spans with a 10% parent-based sampler, a Prometheus <code class="language-plaintext highlighter-rouge">/metrics</code> endpoint, and a multi-stage distroless build in
a six-service Compose stack.</li>
</ul>]]></content><author><name>Raghavendra Singh Chauhan</name><email>raghavendra.swe666@gmail.com</email></author><category term="go" /><category term="gin" /><category term="postgresql" /><category term="gorm" /><category term="opentelemetry" /><category term="docker" /><summary type="html"><![CDATA[A Go and Postgres service that picks unsolved problems by difficulty, runs a timed contest per user, and ships with tracing and metrics in Docker Compose.]]></summary></entry><entry><title type="html">diffu-syn: a tabular diffusion model behind a FastAPI and Celery job API</title><link href="https://raghavendrapara.github.io/rc-says/projects/diffu-syn/" rel="alternate" type="text/html" title="diffu-syn: a tabular diffusion model behind a FastAPI and Celery job API" /><published>2026-11-27T00:00:00+05:30</published><updated>2026-11-27T00:00:00+05:30</updated><id>https://raghavendrapara.github.io/rc-says/projects/diffu-syn</id><content type="html" xml:base="https://raghavendrapara.github.io/rc-says/projects/diffu-syn/"><![CDATA[<h2 id="the-problem">The problem</h2>

<p>Teams often need data that looks like their production tables (same columns, similar distributions) but contains
no real records. A generative model can produce that, but training one is slow and CPU/GPU heavy. If an API does
the training inside the request handler, the request times out, a crash takes the web process down with it, and
there is no way to see what is running.</p>

<p>diffu-syn is my attempt at both halves of that: a small diffusion model for numeric tables, usable as a Python
library (<code class="language-plaintext highlighter-rouge">TabularDiffusion().fit(df).generate(n)</code>), and a service that runs the same code as background jobs. You
upload a CSV, get a task id, poll for status, trigger generation from the trained model, download the synthetic CSV,
and optionally ask for a quality report.</p>

<h2 id="architecture">Architecture</h2>

<div class="diagram">
<svg viewBox="0 0 720 360" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Client calls the FastAPI service, which enqueues jobs in Redis; a Celery worker consumes them, writes results back to Redis and files to a shared data volume; Flower watches Redis.">
  <defs><marker id="diffu-syn-a1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead" /></marker><marker id="diffu-syn-a2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead-accent" /></marker></defs>
  <rect x="180" y="24" width="530" height="316" rx="10" class="dg-group" />
  <text x="196" y="44" class="dg-label">docker compose</text>
  <rect x="20" y="150" width="130" height="56" rx="8" class="dg-box" />
  <text x="85" y="174" text-anchor="middle" class="dg-text">Client</text>
  <text x="85" y="192" text-anchor="middle" class="dg-sub">upload CSV, poll</text>
  <rect x="200" y="150" width="150" height="56" rx="8" class="dg-box" />
  <text x="275" y="174" text-anchor="middle" class="dg-text">API service</text>
  <text x="275" y="192" text-anchor="middle" class="dg-sub">FastAPI + uvicorn</text>
  <rect x="400" y="60" width="150" height="56" rx="8" class="dg-box" />
  <text x="475" y="84" text-anchor="middle" class="dg-text">Redis</text>
  <text x="475" y="102" text-anchor="middle" class="dg-sub">broker + results</text>
  <rect x="400" y="240" width="150" height="56" rx="8" class="dg-box-accent" />
  <text x="475" y="264" text-anchor="middle" class="dg-text">Celery worker</text>
  <text x="475" y="282" text-anchor="middle" class="dg-sub">train / generate / eval</text>
  <rect x="580" y="60" width="115" height="56" rx="8" class="dg-box" />
  <text x="637" y="84" text-anchor="middle" class="dg-text">Flower</text>
  <text x="637" y="102" text-anchor="middle" class="dg-sub">job monitor</text>
  <rect x="580" y="240" width="115" height="56" rx="8" class="dg-box" />
  <text x="637" y="264" text-anchor="middle" class="dg-text">./data volume</text>
  <text x="637" y="282" text-anchor="middle" class="dg-sub">raw, models, out</text>
  <line x1="150" y1="178" x2="198" y2="178" class="dg-line-accent" marker-end="url(#diffu-syn-a2)" />
  <line x1="350" y1="165" x2="398" y2="100" class="dg-line-accent" marker-end="url(#diffu-syn-a2)" />
  <text x="364" y="124" text-anchor="end" class="dg-sub">enqueue</text>
  <line x1="505" y1="116" x2="505" y2="238" class="dg-line-accent" marker-end="url(#diffu-syn-a2)" />
  <text x="512" y="182" class="dg-sub">task</text>
  <line x1="445" y1="240" x2="445" y2="118" class="dg-line-dashed" marker-end="url(#diffu-syn-a1)" />
  <text x="438" y="182" text-anchor="end" class="dg-sub">result</text>
  <line x1="550" y1="268" x2="578" y2="268" class="dg-line-accent" marker-end="url(#diffu-syn-a2)" />
  <line x1="580" y1="88" x2="552" y2="88" class="dg-line-dashed" marker-end="url(#diffu-syn-a1)" />
  <path d="M275,206 L275,318 L637,318 L637,298" fill="none" class="dg-line-dashed" marker-end="url(#diffu-syn-a1)" />
  <text x="456" y="312" text-anchor="middle" class="dg-sub">upload in, synthetic CSV out</text>
</svg>
<p class="diagram-caption">Figure 1. Job flow in the version I ran end to end: the API only stores files and enqueues; the worker does the heavy work and reports back through the Redis result backend.</p>
</div>

<p>The codebase is split into two packages:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">diffusyn.core</code></strong>: the library. <code class="language-plaintext highlighter-rouge">TabularModel</code> (an MLP noise predictor), <code class="language-plaintext highlighter-rouge">DiffusionEngine</code> (the DDPM forward
and reverse processes), <code class="language-plaintext highlighter-rouge">DiffuSynDataset</code> (a Polars-backed <code class="language-plaintext highlighter-rouge">IterableDataset</code>), and <code class="language-plaintext highlighter-rouge">TabularDiffusion</code>, which ties
them together with a min-max scaler, <code class="language-plaintext highlighter-rouge">fit</code> / <code class="language-plaintext highlighter-rouge">generate</code> / <code class="language-plaintext highlighter-rouge">save</code> / <code class="language-plaintext highlighter-rouge">load</code>, and an SDMetrics quality report.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">diffusyn.interface</code></strong>: the service. <code class="language-plaintext highlighter-rouge">api.py</code> (FastAPI routes <code class="language-plaintext highlighter-rouge">/train</code>, <code class="language-plaintext highlighter-rouge">/status/{id}</code>, <code class="language-plaintext highlighter-rouge">/generate</code>,
<code class="language-plaintext highlighter-rouge">/evaluate</code>, <code class="language-plaintext highlighter-rouge">/download/{file}</code>), <code class="language-plaintext highlighter-rouge">worker.py</code> (Celery tasks), <code class="language-plaintext highlighter-rouge">storage.py</code> (a storage interface plus a local-disk
implementation) and <code class="language-plaintext highlighter-rouge">config.py</code> (pydantic-settings, all overridable with <code class="language-plaintext highlighter-rouge">DIFFUSYN_*</code> env vars).</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">POST /train</code> streams the upload to <code class="language-plaintext highlighter-rouge">data/raw/&lt;uuid&gt;.csv</code> and enqueues a training task. The worker trains, saves a
<code class="language-plaintext highlighter-rouge">.pth</code> checkpoint under <code class="language-plaintext highlighter-rouge">data/models/</code>, and returns <code class="language-plaintext highlighter-rouge">{"model_path": ...}</code> as the task result. <code class="language-plaintext highlighter-rouge">POST /generate</code> takes
the <em>training</em> task id, reads its result from Redis to find the checkpoint, and enqueues a generation task that
writes <code class="language-plaintext highlighter-rouge">data/outputs/syn_&lt;uuid&gt;.csv</code>. <code class="language-plaintext highlighter-rouge">/evaluate</code> runs an SDMetrics column-shape report on a worker. The API and
worker containers share the <code class="language-plaintext highlighter-rouge">./data</code> mount, which is how the model file written by one is visible to the other.
Flower runs as a separate container for watching the queue.</p>

<h2 id="key-design-decisions">Key design decisions</h2>

<p><strong>Celery workers instead of training in the request.</strong> FastAPI’s <code class="language-plaintext highlighter-rouge">BackgroundTasks</code> would have been simpler (no
broker, no second container), but it runs in the API process: a long PyTorch job competes with request handling and
dies with it. Celery puts training in its own process with retries (<code class="language-plaintext highlighter-rouge">self.retry(countdown=60, max_retries=3)</code>),
event reporting (<code class="language-plaintext highlighter-rouge">-E</code>) and a dashboard (Flower). The cost is two more moving parts (Redis and the worker) and the
need for a shared filesystem between API and worker.</p>

<p><strong>The task id is the handle; there is no database.</strong> Generation looks up the training task’s result in the Celery
result backend to find the model path. That avoids a jobs table and a migration story, at the cost of durability:
Redis results expire (Celery’s default is one day), so after that a model can no longer be found by id even though
the file is still on disk. A small jobs table is the obvious next step.</p>

<p><strong>A storage interface before there is a second backend.</strong> <code class="language-plaintext highlighter-rouge">StorageService</code> is a <code class="language-plaintext highlighter-rouge">typing.Protocol</code> with
<code class="language-plaintext highlighter-rouge">save_upload</code> and <code class="language-plaintext highlighter-rouge">get_local_path</code>; <code class="language-plaintext highlighter-rouge">LocalStorage</code> writes uploads with <code class="language-plaintext highlighter-rouge">aiofiles</code> in 1 MB chunks so a large CSV
never sits in API memory. Workers ask for a <em>local path</em>, so an S3 implementation would download to a temp dir
first and the training code would not change.</p>

<p><strong>Library first, server as an extra.</strong> <code class="language-plaintext highlighter-rouge">pyproject.toml</code> keeps the core deps (torch, polars, sdmetrics) separate
from a <code class="language-plaintext highlighter-rouge">[server]</code> extra (FastAPI, Celery, Redis). The dev Dockerfile installs CPU-only PyTorch in its own layer
before copying <code class="language-plaintext highlighter-rouge">pyproject.toml</code>, so source edits do not trigger a multi-GB reinstall. <code class="language-plaintext highlighter-rouge">Dockerfile.prod</code> is a
two-stage build: dependencies go into a venv in a builder image, and the runtime image copies only the venv and
runs as a non-root user.</p>

<p><strong>DDPM on min-max-scaled numbers rather than a GAN.</strong> Diffusion training is a plain regression (predict the noise
that was added), so it is stable without GAN tricks. The price is slow sampling: generation runs the network 1,000
times per batch. Data is scaled to [-1, 1] to match the Gaussian noise, and the scaler’s min/max values are saved
inside the checkpoint so <code class="language-plaintext highlighter-rouge">load()</code> restores both the model and the inverse transform.</p>

<h2 id="inside-the-code">Inside the code</h2>

<p>The heart of the model is about twenty lines in <code class="language-plaintext highlighter-rouge">core/diffusion.py</code>. Training picks a random timestep per row,
noises the data in closed form, and asks the network to predict that noise:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">q_sample</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x_0</span><span class="p">,</span> <span class="n">t</span><span class="p">,</span> <span class="n">noise</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="s">""" Forward Process (Add Noise) """</span>
    <span class="k">if</span> <span class="n">noise</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">noise</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">randn_like</span><span class="p">(</span><span class="n">x_0</span><span class="p">)</span>
    <span class="n">sqrt_alphas_cumprod_t</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">alphas_cumprod</span><span class="p">[</span><span class="n">t</span><span class="p">])[:,</span> <span class="bp">None</span><span class="p">]</span>
    <span class="n">sqrt_one_minus_alphas_cumprod_t</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">sqrt</span><span class="p">(</span>
        <span class="mi">1</span> <span class="o">-</span> <span class="bp">self</span><span class="p">.</span><span class="n">alphas_cumprod</span><span class="p">[</span><span class="n">t</span><span class="p">])[:,</span> <span class="bp">None</span><span class="p">]</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">sqrt_alphas_cumprod_t</span> <span class="o">*</span> <span class="n">x_0</span>
            <span class="o">+</span> <span class="n">sqrt_one_minus_alphas_cumprod_t</span> <span class="o">*</span> <span class="n">noise</span><span class="p">),</span> <span class="n">noise</span>

<span class="k">def</span> <span class="nf">compute_loss</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x_0</span><span class="p">):</span>
    <span class="s">""" Training Loss """</span>
    <span class="n">batch_size</span> <span class="o">=</span> <span class="n">x_0</span><span class="p">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
    <span class="n">t</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="bp">self</span><span class="p">.</span><span class="n">steps</span><span class="p">,</span> <span class="p">(</span><span class="n">batch_size</span><span class="p">,),</span> <span class="n">device</span><span class="o">=</span><span class="bp">self</span><span class="p">.</span><span class="n">device</span><span class="p">)</span>
    <span class="n">noise</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">randn_like</span><span class="p">(</span><span class="n">x_0</span><span class="p">)</span>
    <span class="n">x_t</span><span class="p">,</span> <span class="n">real_noise</span> <span class="o">=</span> <span class="bp">self</span><span class="p">.</span><span class="n">q_sample</span><span class="p">(</span><span class="n">x_0</span><span class="p">,</span> <span class="n">t</span><span class="p">,</span> <span class="n">noise</span><span class="p">)</span>
    <span class="n">predicted_noise</span> <span class="o">=</span> <span class="bp">self</span><span class="p">.</span><span class="n">model</span><span class="p">(</span><span class="n">x_t</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">F</span><span class="p">.</span><span class="n">mse_loss</span><span class="p">(</span><span class="n">predicted_noise</span><span class="p">,</span> <span class="n">real_noise</span><span class="p">)</span>
</code></pre></div></div>

<p>Because <code class="language-plaintext highlighter-rouge">alphas_cumprod</code> is precomputed, the model never has to step through 1,000 noising steps during training;
any timestep is one multiply-add away. In a quick local run (5,000 rows, two columns, 40 epochs on CPU) the
generated columns came back with means and standard deviations close to the originals.</p>

<p>The chaining between jobs lives in <code class="language-plaintext highlighter-rouge">interface/api.py</code>. The generate endpoint refuses to queue work against a model
that does not exist yet:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">app</span><span class="p">.</span><span class="n">post</span><span class="p">(</span><span class="s">"/generate"</span><span class="p">)</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">trigger_generation</span><span class="p">(</span><span class="n">request</span><span class="p">:</span> <span class="n">GenerateRequest</span><span class="p">,</span> <span class="n">req</span><span class="p">:</span> <span class="n">Request</span><span class="p">):</span>
    <span class="n">training_result</span> <span class="o">=</span> <span class="n">celery_app</span><span class="p">.</span><span class="n">AsyncResult</span><span class="p">(</span><span class="n">request</span><span class="p">.</span><span class="n">task_id</span><span class="p">)</span>

    <span class="k">if</span> <span class="ow">not</span> <span class="n">training_result</span><span class="p">.</span><span class="n">successful</span><span class="p">():</span>
        <span class="k">raise</span> <span class="n">HTTPException</span><span class="p">(</span>
            <span class="n">status_code</span><span class="o">=</span><span class="mi">400</span><span class="p">,</span>
            <span class="n">detail</span><span class="o">=</span><span class="sa">f</span><span class="s">"Training not complete or failed. "</span>
                   <span class="sa">f</span><span class="s">"Status: </span><span class="si">{</span><span class="n">training_result</span><span class="p">.</span><span class="n">status</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>

    <span class="n">full_model_path</span> <span class="o">=</span> <span class="n">training_result</span><span class="p">.</span><span class="n">result</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"model_path"</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">full_model_path</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">HTTPException</span><span class="p">(</span>
            <span class="n">status_code</span><span class="o">=</span><span class="mi">404</span><span class="p">,</span>
            <span class="n">detail</span><span class="o">=</span><span class="s">"Model info not found in training result"</span><span class="p">)</span>
    <span class="c1"># … enqueue the generation task, return its id and a download URL
</span></code></pre></div></div>

<p>This is where the “task id as handle” decision shows up: the API stays stateless, and Redis is the source of truth
for whether a model is ready.</p>

<h2 id="running-it">Running it</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># redis, api on :8000, worker, flower on :5555</span>
docker compose up <span class="nt">-d</span> <span class="nt">--build</span>
<span class="c"># 50 training jobs from 10 threads; watch Flower drain the queue</span>
python tests/stress_test.py
pytest tests/unit tests/api
<span class="c"># production image: multi-stage build, non-root user</span>
docker compose <span class="nt">-f</span> docker-compose.prod.yml up <span class="nt">-d</span> <span class="nt">--build</span>
</code></pre></div></div>

<h2 id="what-id-do-next">What I’d do next</h2>

<p>The honest state of the repo:</p>

<ul>
  <li><strong>The latest commit is a scaffold, not a working path.</strong> In July 2026 I added <code class="language-plaintext highlighter-rouge">core/orchestration.py</code> and
<code class="language-plaintext highlighter-rouge">core/streaming.py</code> to sketch named GPU queues and chunked training. The <code class="language-plaintext highlighter-rouge">/train</code> and <code class="language-plaintext highlighter-rouge">/generate</code> routes now go
through that code, and it is not finished: the worker tasks it calls use placeholder models, the compose worker
does not subscribe to the new queues, and the orchestrator reads a different env var for its Redis URL. The
train, generate, download flow above is the January 2026 version (commit <code class="language-plaintext highlighter-rouge">1c62e98</code>), which I ran end to end
against a real Redis and Celery worker. Restoring that path under the new names is the first fix.</li>
  <li><strong>Memory:</strong> <code class="language-plaintext highlighter-rouge">fit()</code> reads the whole CSV with <code class="language-plaintext highlighter-rouge">pl.read_csv</code> because the scaler needs global min/max. Streaming
training needs a first pass for statistics, then a batched pass. The file-path branch of <code class="language-plaintext highlighter-rouge">DiffuSynDataset.__iter__</code>
is also broken (it checks for an attribute it never sets); only the in-memory branch is used today.</li>
  <li><strong>Data types:</strong> numeric columns only; categoricals must be encoded beforehand. Generated values are not clipped
to [-1, 1] before un-scaling, so some fall slightly outside the training range.</li>
  <li><strong>Ops:</strong> the CI workflow file and Makefile are empty, there is no health endpoint, no auth, and logs are <code class="language-plaintext highlighter-rouge">print</code>.
One unit test is out of date (validation moved into <code class="language-plaintext highlighter-rouge">__init__</code>). Opacus is a dependency but differential privacy
is not implemented.</li>
</ul>

<h2 id="skills-this-shows">Skills this shows</h2>

<ul>
  <li><strong>Async job orchestration:</strong> FastAPI producer, Celery consumer, Redis broker and result backend, retries with
back-off, job chaining by task id, Flower for visibility.</li>
  <li><strong>Containerisation:</strong> layer-cached CPU PyTorch install, multi-stage production image with a venv and non-root user,
compose with Redis health-check gating and shared volumes.</li>
  <li><strong>Backend API design:</strong> chunked async uploads, config through env-prefixed pydantic settings, a storage interface
that keeps S3 a drop-in change.</li>
  <li><strong>Applied ML:</strong> a DDPM implemented from the equations (beta schedule, closed-form forward process, posterior
variance in sampling), sinusoidal time embeddings, residual MLP, checkpointing model plus scaler, SDMetrics
evaluation.</li>
  <li><strong>Testing and load:</strong> pytest with a mocked Celery result backend, and a threaded stress script that pushes jobs
through the real API.</li>
</ul>]]></content><author><name>Raghavendra Singh Chauhan</name><email>raghavendra.swe666@gmail.com</email></author><category term="python" /><category term="pytorch" /><category term="fastapi" /><category term="celery" /><category term="redis" /><category term="docker" /><summary type="html"><![CDATA[A small PyTorch diffusion model for numeric tables, wrapped in an async train/generate/evaluate API with Celery workers, Redis and Docker.]]></summary></entry><entry><title type="html">dots-agent: an LLM video pipeline with human approval gates and an adversarial fact-checker</title><link href="https://raghavendrapara.github.io/rc-says/projects/dots-agent/" rel="alternate" type="text/html" title="dots-agent: an LLM video pipeline with human approval gates and an adversarial fact-checker" /><published>2026-11-27T00:00:00+05:30</published><updated>2026-11-27T00:00:00+05:30</updated><id>https://raghavendrapara.github.io/rc-says/projects/dots-agent</id><content type="html" xml:base="https://raghavendrapara.github.io/rc-says/projects/dots-agent/"><![CDATA[<h2 id="the-problem">The problem</h2>

<p>An explainer video that links a few separate developments (“this rate decision, this commodity price, this election”) into one story is mostly research and writing. Language models are good at both and also good at sounding certain about things they made up. In finance and politics a confident wrong number or an opinion stated as fact is the worst possible failure.</p>

<p>So the goal was not “generate a video”. It was: let the model do the slow work (finding sources, drafting, cutting Shorts, building charts) while a person keeps control of the two decisions that matter, which story to tell and which claims survive. Everything runs from a Telegram chat on my own machine, so a review takes a few taps on a phone.</p>

<h2 id="architecture">Architecture</h2>

<div class="diagram">
<svg viewBox="0 0 740 410" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Pipeline: radar or thesis outline, then a human gate, then research, script, critic, a second human gate for claim review, voice, visuals, render and package. A Telegram bot drives the graph and SQLite stores checkpoints and metrics.">
  <defs><marker id="dots-agent-a1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead" /></marker><marker id="dots-agent-a2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead-accent" /></marker></defs>
  <text x="20" y="26" class="dg-label">Two entry flows</text>
  <rect x="20" y="40" width="140" height="56" rx="8" class="dg-box" />
  <text x="90" y="64" text-anchor="middle" class="dg-text">RSS radar</text>
  <text x="90" y="82" text-anchor="middle" class="dg-sub">ranked angles</text>
  <rect x="20" y="130" width="140" height="56" rx="8" class="dg-box" />
  <text x="90" y="154" text-anchor="middle" class="dg-text">Thesis outline</text>
  <text x="90" y="172" text-anchor="middle" class="dg-sub">my notes + clippings</text>
  <rect x="190" y="40" width="160" height="56" rx="8" class="dg-box-accent" />
  <text x="270" y="64" text-anchor="middle" class="dg-text">Gate: pick angle</text>
  <text x="270" y="82" text-anchor="middle" class="dg-sub">or regenerate</text>
  <rect x="190" y="130" width="160" height="56" rx="8" class="dg-box-accent" />
  <text x="270" y="154" text-anchor="middle" class="dg-text">Gate: outline</text>
  <text x="270" y="172" text-anchor="middle" class="dg-sub">approve / revise / cancel</text>
  <rect x="380" y="85" width="160" height="56" rx="8" class="dg-box" />
  <text x="460" y="109" text-anchor="middle" class="dg-text">Research</text>
  <text x="460" y="127" text-anchor="middle" class="dg-sub">web search, FRED, WB</text>
  <rect x="570" y="85" width="150" height="56" rx="8" class="dg-box" />
  <text x="645" y="109" text-anchor="middle" class="dg-text">Script</text>
  <text x="645" y="127" text-anchor="middle" class="dg-sub">fact / inference tags</text>
  <rect x="570" y="220" width="150" height="56" rx="8" class="dg-box" />
  <text x="645" y="244" text-anchor="middle" class="dg-text">Critic</text>
  <text x="645" y="262" text-anchor="middle" class="dg-sub">claim ledger</text>
  <rect x="380" y="220" width="160" height="56" rx="8" class="dg-box-accent" />
  <text x="460" y="244" text-anchor="middle" class="dg-text">Gate: claim review</text>
  <text x="460" y="262" text-anchor="middle" class="dg-sub">keep / suggestion / cut</text>
  <rect x="190" y="220" width="160" height="56" rx="8" class="dg-box" />
  <text x="270" y="244" text-anchor="middle" class="dg-text">Voice</text>
  <text x="270" y="262" text-anchor="middle" class="dg-sub">TTS + word timings</text>
  <rect x="20" y="220" width="140" height="56" rx="8" class="dg-box" />
  <text x="90" y="244" text-anchor="middle" class="dg-text">Visuals</text>
  <text x="90" y="262" text-anchor="middle" class="dg-sub">charts, maps, B-roll</text>
  <rect x="20" y="320" width="140" height="56" rx="8" class="dg-box" />
  <text x="90" y="344" text-anchor="middle" class="dg-text">Render</text>
  <text x="90" y="362" text-anchor="middle" class="dg-sub">Remotion + ffmpeg</text>
  <rect x="190" y="320" width="160" height="56" rx="8" class="dg-box" />
  <text x="270" y="344" text-anchor="middle" class="dg-text">Package + upload</text>
  <text x="270" y="362" text-anchor="middle" class="dg-sub">metadata, YouTube API</text>
  <rect x="395" y="305" width="335" height="90" rx="10" class="dg-group" />
  <text x="718" y="322" text-anchor="end" class="dg-label">Control and state</text>
  <rect x="410" y="330" width="140" height="52" rx="8" class="dg-box" />
  <text x="480" y="352" text-anchor="middle" class="dg-text">Telegram bot</text>
  <text x="480" y="369" text-anchor="middle" class="dg-sub">invoke / resume</text>
  <rect x="570" y="330" width="150" height="52" rx="8" class="dg-box" />
  <text x="645" y="352" text-anchor="middle" class="dg-text">SQLite</text>
  <text x="645" y="369" text-anchor="middle" class="dg-sub">checkpoints, metrics</text>
  <line x1="160" y1="68" x2="190" y2="68" class="dg-line" marker-end="url(#dots-agent-a1)" />
  <line x1="160" y1="158" x2="190" y2="158" class="dg-line" marker-end="url(#dots-agent-a1)" />
  <line x1="350" y1="68" x2="380" y2="100" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="350" y1="158" x2="380" y2="126" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="540" y1="113" x2="570" y2="113" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="645" y1="141" x2="645" y2="220" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="570" y1="248" x2="540" y2="248" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="380" y1="248" x2="350" y2="248" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="190" y1="248" x2="160" y2="248" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="90" y1="276" x2="90" y2="320" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="160" y1="348" x2="190" y2="348" class="dg-line-accent" marker-end="url(#dots-agent-a2)" />
  <line x1="480" y1="330" x2="460" y2="276" class="dg-line-dashed" marker-end="url(#dots-agent-a1)" />
</svg>
<p class="diagram-caption">Figure 1. The LangGraph pipeline. Highlighted boxes are the points where the graph pauses for a human decision; the Telegram bot resumes it.</p>
</div>

<p>The pipeline is a LangGraph <code class="language-plaintext highlighter-rouge">StateGraph</code> with twelve nodes. Every stage lives in its own module under <code class="language-plaintext highlighter-rouge">dots/stages/</code> and writes a typed pydantic artifact as JSON into <code class="language-plaintext highlighter-rouge">runs/&lt;id&gt;/</code>, so each step can be inspected and cached on its own.</p>

<p>There are two ways in. The news flow scans a list of RSS feeds from the last 48 hours, deduplicates headlines and asks a model for ranked angles; I pick one in Telegram or ask for new ones. The thesis flow, the one I use most, starts from my own notes plus links I forwarded to the bot during the week (article text extracted with trafilatura). The model turns that into a one-page outline with beats, the strongest counterargument and scenarios with rough odds and signposts. I approve it, send revision notes (which loop back to the outline node) or cancel.</p>

<p>After that the path is shared:</p>

<ul>
  <li><strong>Research</strong> returns a fact pack: each fact has a claim, source URL, publisher, date and snippet. Thesis episodes search only a curated list of domains (official data, major outlets, think tanks) from <code class="language-plaintext highlighter-rouge">config.yaml</code>. The model can <em>request</em> chart series by FRED series ID or World Bank indicator, and code fetches the numbers from those APIs.</li>
  <li><strong>Script</strong> writes sentences, each tagged <code class="language-plaintext highlighter-rouge">fact</code> (with fact IDs) or <code class="language-plaintext highlighter-rouge">inference</code>, plus a visual hint and Shorts cut points.</li>
  <li><strong>Critic</strong> reviews the script against the fact pack and returns a claim ledger: verdict (keep, soften, cut), confidence, reason, a competing explanation, suggested rewrite and risk flags.</li>
  <li><strong>Claim review</strong> is the second human gate. I get the full script as a file plus one Telegram message per doubtful sentence with Keep / Use suggestion / Cut buttons, or I reply with my own text.</li>
  <li><strong>Voice</strong> calls ElevenLabs with timestamps, so word timings drive captions and sentence timings drive scene cuts.</li>
  <li><strong>Visuals</strong> builds a Remotion timeline: FRED/World Bank charts, maps, stat cards, an animated “dots board”, and stock B-roll from Pexels/Pixabay with each licence logged.</li>
  <li><strong>Render</strong> shells out to Remotion for the 16:9 video, 9:16 Shorts and thumbnails, then normalises loudness with ffmpeg. <strong>Package</strong> writes titles, a description with sources and disclosures, and chapters; an optional step uploads to YouTube.</li>
</ul>

<p>The render side is a small TypeScript/React project (Remotion) that only reads the timeline JSON; it has no logic of its own about content.</p>

<h2 id="key-design-decisions">Key design decisions</h2>

<p><strong>LangGraph <code class="language-plaintext highlighter-rouge">interrupt()</code> with a SQLite checkpointer, instead of a hand-written state machine.</strong> The gates are plain <code class="language-plaintext highlighter-rouge">interrupt()</code> calls inside nodes, and the bot resumes them with <code class="language-plaintext highlighter-rouge">Command(resume=...)</code> keyed by run ID as the thread ID. Because state is checkpointed after every node, a crash in rendering does not lose a paid-for research pass: <code class="language-plaintext highlighter-rouge">/retry &lt;run&gt;</code> re-invokes the graph and it continues from the failed node. I also added <code class="language-plaintext highlighter-rouge">/redo &lt;run&gt; &lt;stage&gt;</code>, which uses <code class="language-plaintext highlighter-rouge">update_state(..., as_node=...)</code> to rewind a run to an earlier stage and deletes only the cached files downstream of it. The cost is a dependency on LangGraph’s checkpoint semantics, which I covered with offline tests that drive the whole graph through both gates.</p>

<p><strong>Forced tool calls for structured output, plus a validate-and-repair loop.</strong> Every structured answer is requested through a single <code class="language-plaintext highlighter-rouge">submit</code> tool whose input schema is the pydantic model (with <code class="language-plaintext highlighter-rouge">$ref</code>s inlined because one provider rejects them). The alternative, parsing JSON from free text, broke on truncated or fenced output. When the answer is cut off, fails validation, or fails a semantic check such as “fewer than 10 sourced facts”, the loop re-asks with the specific error. There are fallbacks for models that reject forced <code class="language-plaintext highlighter-rouge">tool_choice</code>: auto tool choice with an instruction, then JSON mode.</p>

<p><strong>Two-phase research so a cheaper model can own a stage.</strong> Phase A uses Anthropic’s server-side web search to write cited notes as plain text; phase B has whichever model is configured for that stage structure the notes into the schema. That lets me run outline and script on DeepSeek and keep research and critic on Claude, set per stage in <code class="language-plaintext highlighter-rouge">config.yaml</code>. Without a DeepSeek key everything falls back to Claude. The search notes are cached per run and per prompt, so a failed structuring pass does not pay for the search again.</p>

<p><strong>Facts and numbers are separated from the model’s prose.</strong> A script sentence marked <code class="language-plaintext highlighter-rouge">fact</code> that cites no fact ID, or an ID not in the pack, is demoted to <code class="language-plaintext highlighter-rouge">inference</code>, and with <code class="language-plaintext highlighter-rouge">always_review_inferences</code> on, the critic’s reviewed inferences go to me. Chart data is never written by the model: <code class="language-plaintext highlighter-rouge">ResearchDraft</code> has no datasets field at all, and before a chart is placed behind a sentence, <code class="language-plaintext highlighter-rouge">chart_matches</code> checks that any figure the sentence quotes appears in the series within 3%. Otherwise the scene falls back to a stat card or ambient motion.</p>

<p><strong>A critic from a different model family, told to disagree.</strong> The critic’s system prompt rewards catching errors, and the prompt assumes the writer is biased toward the thesis. In the current config the script comes from DeepSeek and the critic is Claude, so the check is not a model grading its own work. Only items that are not a clean “keep”, carry a flag, fall under the confidence threshold (0.75) or are inferences reach me, sorted by lowest confidence first; everything else passes without my attention.</p>

<h2 id="inside-the-code">Inside the code</h2>

<p>The review gate. The critic’s ledger is filtered down to what needs a human, the graph pauses, and the decisions that come back from Telegram are applied to the script:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># dots/stages/critic.py: what reaches the human
</span><span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="n">ledger</span><span class="p">.</span><span class="n">reviews</span><span class="p">:</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">by_id</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="n">r</span><span class="p">.</span><span class="n">sentence_id</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">s</span><span class="p">:</span>
        <span class="k">continue</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">r</span><span class="p">.</span><span class="n">verdict</span> <span class="o">!=</span> <span class="s">"keep"</span> <span class="ow">or</span> <span class="n">r</span><span class="p">.</span><span class="n">flags</span> <span class="ow">or</span> <span class="n">r</span><span class="p">.</span><span class="n">confidence</span> <span class="o">&lt;</span> <span class="n">th</span>
            <span class="ow">or</span> <span class="p">(</span><span class="n">always_inf</span> <span class="ow">and</span> <span class="n">s</span><span class="p">.</span><span class="n">kind</span> <span class="o">==</span> <span class="s">"inference"</span><span class="p">)):</span>
        <span class="n">out</span><span class="p">.</span><span class="n">append</span><span class="p">({</span><span class="s">"sentence_id"</span><span class="p">:</span> <span class="n">s</span><span class="p">.</span><span class="nb">id</span><span class="p">,</span> <span class="s">"kind"</span><span class="p">:</span> <span class="n">s</span><span class="p">.</span><span class="n">kind</span><span class="p">,</span> <span class="p">...})</span>
<span class="n">out</span><span class="p">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="p">[</span><span class="s">"confidence"</span><span class="p">])</span>

<span class="c1"># dots/graph.py: the node pauses until the bot resumes it
</span><span class="k">def</span> <span class="nf">n_review</span><span class="p">(</span><span class="n">s</span><span class="p">:</span> <span class="n">State</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">State</span><span class="p">:</span>
    <span class="c1"># … load script and ledger
</span>    <span class="n">items</span> <span class="o">=</span> <span class="n">critic</span><span class="p">.</span><span class="n">items_for_review</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="n">led</span><span class="p">)</span>
    <span class="n">resp</span> <span class="o">=</span> <span class="p">(</span><span class="n">interrupt</span><span class="p">({</span><span class="s">"type"</span><span class="p">:</span> <span class="s">"review"</span><span class="p">,</span> <span class="s">"items"</span><span class="p">:</span> <span class="n">items</span><span class="p">,</span> <span class="s">"script"</span><span class="p">:</span> <span class="n">s</span><span class="p">[</span><span class="s">"script"</span><span class="p">]})</span>
            <span class="k">if</span> <span class="n">items</span> <span class="k">else</span> <span class="p">{</span><span class="s">"decisions"</span><span class="p">:</span> <span class="p">{}})</span>
    <span class="n">decisions</span> <span class="o">=</span> <span class="n">resp</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"decisions"</span><span class="p">,</span> <span class="p">{})</span>
    <span class="c1"># … log each decision next to the critic's verdict in metrics.db
</span>    <span class="n">final</span> <span class="o">=</span> <span class="n">critic</span><span class="p">.</span><span class="n">apply_decisions</span><span class="p">(</span><span class="n">sc</span><span class="p">,</span> <span class="n">decisions</span><span class="p">,</span> <span class="n">suggestions</span><span class="p">)</span>
</code></pre></div></div>

<p>Logging the critic’s verdict next to my decision in <code class="language-plaintext highlighter-rouge">metrics.db</code> gives me data on how often I overrule the critic, which is the obvious way to tune the threshold later.</p>

<p>The repair loop that every LLM call goes through. The budget is checked before each attempt, and each retry carries the concrete reason the last answer was rejected:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">retries</span> <span class="o">+</span> <span class="mi">2</span> <span class="k">if</span> <span class="n">check</span> <span class="k">else</span> <span class="n">retries</span> <span class="o">+</span> <span class="mi">1</span><span class="p">):</span>
    <span class="n">_budget_check</span><span class="p">(</span><span class="n">run_id</span><span class="p">,</span> <span class="n">stage</span><span class="p">)</span>
    <span class="n">data</span><span class="p">,</span> <span class="n">stop</span> <span class="o">=</span> <span class="n">structured</span><span class="p">(</span><span class="n">run_id</span><span class="p">,</span> <span class="n">stage</span><span class="p">,</span> <span class="n">system</span><span class="p">,</span> <span class="n">prompt</span><span class="p">,</span>
                            <span class="n">schema_json</span><span class="p">,</span> <span class="n">st</span><span class="p">[</span><span class="s">"model"</span><span class="p">])</span>
    <span class="k">if</span> <span class="n">stop</span> <span class="o">==</span> <span class="s">"max_tokens"</span><span class="p">:</span>
        <span class="n">prompt</span> <span class="o">=</span> <span class="n">user</span> <span class="o">+</span> <span class="s">"</span><span class="se">\n\n</span><span class="s">Your previous answer was cut off ..."</span>
        <span class="k">continue</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">schema</span><span class="p">.</span><span class="n">model_validate</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">ValidationError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="n">prompt</span> <span class="o">=</span> <span class="p">(</span><span class="n">user</span> <span class="o">+</span> <span class="s">"</span><span class="se">\n\n</span><span class="s">Your previous answer failed validation:</span><span class="se">\n</span><span class="s">"</span>
                  <span class="sa">f</span><span class="s">"</span><span class="si">{</span><span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="p">)[</span><span class="si">:</span><span class="mi">1500</span><span class="p">]</span><span class="si">}</span><span class="se">\n</span><span class="s">Previous answer:</span><span class="se">\n</span><span class="s">"</span>
                  <span class="sa">f</span><span class="s">"</span><span class="si">{</span><span class="n">json</span><span class="p">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">data</span><span class="p">)[</span><span class="si">:</span><span class="mi">6000</span><span class="p">]</span><span class="si">}</span><span class="se">\n</span><span class="s">Fix it."</span><span class="p">)</span>
        <span class="k">continue</span>
    <span class="n">problem</span> <span class="o">=</span> <span class="n">check</span><span class="p">(</span><span class="n">result</span><span class="p">)</span> <span class="k">if</span> <span class="n">check</span> <span class="k">else</span> <span class="bp">None</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">problem</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">result</span>
    <span class="c1"># … same repair prompt, carrying the semantic problem
</span><span class="k">raise</span> <span class="nb">RuntimeError</span><span class="p">(</span><span class="sa">f</span><span class="s">"</span><span class="si">{</span><span class="n">stage</span><span class="si">}</span><span class="s">: could not get valid output: </span><span class="si">{</span><span class="n">last_err</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
</code></pre></div></div>

<p>Around this sit the other reliability pieces: an <code class="language-plaintext highlighter-rouge">httpx</code> wrapper with exponential backoff on 429/5xx that honours <code class="language-plaintext highlighter-rouge">Retry-After</code>; B-roll downloads that are rejected when the byte count does not match <code class="language-plaintext highlighter-rouge">Content-Length</code>; a stage cache keyed by a hash of each stage’s input, so voice is only regenerated (and paid for) when the narration text changes; review taps persisted to disk so a bot restart mid-review loses nothing; and a YouTube upload that records each finished part, so tapping the button again skips what is already uploaded. Every LLM call and TTS request is priced from a table in config and written to SQLite, which is what the per-run dollar cap reads.</p>

<h2 id="running-it">Running it</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pip <span class="nb">install</span> <span class="nt">-r</span> requirements.txt
<span class="nb">cd </span>render <span class="o">&amp;&amp;</span> npm <span class="nb">install</span> <span class="o">&amp;&amp;</span> npx remotion browser ensure <span class="o">&amp;&amp;</span> <span class="nb">cd</span> ..
<span class="nb">cp</span> .env.example .env        <span class="c"># fill in API keys and the allowed Telegram chat</span>
python <span class="nt">-m</span> dots doctor       <span class="c"># checks env vars and makes live calls to each API</span>
python <span class="nt">-m</span> dots sample       <span class="c"># renders a 12 s offline sample, no API calls</span>
python <span class="nt">-m</span> pytest <span class="nt">-q</span>         <span class="c"># offline tests (28 pass)</span>
python <span class="nt">-m</span> dots bot          <span class="c"># long-polling Telegram controller</span>
</code></pre></div></div>

<h2 id="what-id-do-next">What I’d do next</h2>

<ul>
  <li><strong>Give the critic web search.</strong> The README says the critic spot-checks claims on the web, but the code does not: it only checks the script against the research pack. A claim that is wrong in the pack itself can only be caught by me.</li>
  <li><strong>Enforce critic coverage.</strong> The prompt asks for a review of every inference, but the code only routes sentences the critic actually returned. A sentence the critic skipped is kept without reaching me. The fix is to treat any unreviewed inference as a review item.</li>
  <li><strong>Gate TTS on the budget.</strong> The cap is checked before LLM calls only. ElevenLabs spend is logged and counted, but voice generation does not check the cap first, and a single LLM call can overshoot it.</li>
  <li><strong>Score the prediction ledger.</strong> Approved scenarios are saved with odds, signposts and horizons, but nothing scores them yet.</li>
  <li><strong>Offload rendering.</strong> Rendering is local; the README mentions Cloud Run or Remotion Lambda as a fallback, but that is not built.</li>
  <li>The bot is single-user by design (one allowed chat ID), and the graph runs in a thread from the bot process, so there is no queue for multiple concurrent runs.</li>
</ul>

<h2 id="skills-this-shows">Skills this shows</h2>

<ul>
  <li><strong>AI engineering:</strong> LangGraph graph with conditional edges, <code class="language-plaintext highlighter-rouge">interrupt()</code> gates and checkpoint rewind; schema-forced tool output with validate-and-repair; per-stage model routing across two providers; two-phase search-then-structure research.</li>
  <li><strong>Responsible AI:</strong> fact/inference tagging with automatic demotion of uncited facts, a separate-family adversarial critic, a human claim-review gate, chart numbers only from official APIs, synthetic-voice and disclaimer text added to every description.</li>
  <li><strong>Backend reliability:</strong> retries with backoff and <code class="language-plaintext highlighter-rouge">Retry-After</code>, truncation checks, input-hash stage caching, idempotent resumable uploads, error reporting from the bot with full tracebacks to a log file.</li>
  <li><strong>Cost control and observability:</strong> per-call cost accounting in SQLite, a per-run budget cap, cached paid searches, stage timings and review decisions recorded for later analysis.</li>
  <li><strong>Integration:</strong> Anthropic, DeepSeek (OpenAI-compatible), FRED, World Bank, ElevenLabs, Pexels/Pixabay, YouTube Data API with OAuth, Telegram, and a TypeScript Remotion renderer driven by JSON.</li>
  <li><strong>Testing:</strong> 28 offline pytest tests with fake API clients, including a full graph run through both gates and a <code class="language-plaintext highlighter-rouge">/redo</code> rewind.</li>
</ul>

<p>The code is private; I’m happy to walk through it in an interview.</p>]]></content><author><name>Raghavendra Singh Chauhan</name><email>raghavendra.swe666@gmail.com</email></author><category term="python" /><category term="langgraph" /><category term="llm" /><category term="human-in-the-loop" /><category term="telegram" /><category term="remotion" /><summary type="html"><![CDATA[A LangGraph pipeline that researches, scripts, fact-checks, voices and renders explainer videos, with two human gates run from Telegram.]]></summary></entry><entry><title type="html">Social-Distro (DataHub): an async RAG indexing and query backend in Spring Boot</title><link href="https://raghavendrapara.github.io/rc-says/projects/social-distro/" rel="alternate" type="text/html" title="Social-Distro (DataHub): an async RAG indexing and query backend in Spring Boot" /><published>2026-11-27T00:00:00+05:30</published><updated>2026-11-27T00:00:00+05:30</updated><id>https://raghavendrapara.github.io/rc-says/projects/social-distro</id><content type="html" xml:base="https://raghavendrapara.github.io/rc-says/projects/social-distro/"><![CDATA[<h2 id="the-problem">The problem</h2>

<p>The repository is <code class="language-plaintext highlighter-rouge">social-distro</code>; inside the code the application is called DataHub (<code class="language-plaintext highlighter-rouge">com.raghav.datahub</code>). The unit of
data is a <strong>pod</strong>: a named collection of text items owned by a user. A user creates a pod, adds items to it, starts an
indexing job, and then asks questions that should be answered only from that pod’s content.</p>

<p>Two things made this more than a CRUD app. Turning text into embeddings is slow (each item is a network call to a model
server), so indexing has to run in the background and report progress. And one user with a large pod should not hold up
everyone else’s indexing. I built this to work through those problems in Java, and moved it through three versions:
an in-memory prototype, an in-process virtual-thread worker pool, and finally the Kafka-based pipeline described here.</p>

<h2 id="architecture">Architecture</h2>

<div class="diagram">
<svg viewBox="0 0 740 370" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Architecture: the React UI calls the Spring Boot API. The API stores pods and jobs in Postgres and publishes a job event to the pod-indexing-jobs Kafka topic. A job worker claims the job and fans out one event per item to the item-indexing-events topic. Item workers call the TEI embedding server, which is cached in Redis, and upsert vectors into pgvector. Failed items go to a dead-letter topic. Queries embed the question, run a nearest-neighbour search in pgvector, and send the context to an LLM.">
  <defs>
    <marker id="social-distro-a1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead" /></marker>
    <marker id="social-distro-a2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" class="dg-arrowhead-accent" /></marker>
  </defs>
  <rect x="20" y="30" width="140" height="56" rx="8" class="dg-box" />
  <text x="90" y="54" text-anchor="middle" class="dg-text">React UI</text>
  <text x="90" y="72" text-anchor="middle" class="dg-sub">Vite, TanStack Query</text>
  <rect x="200" y="30" width="150" height="56" rx="8" class="dg-box-accent" />
  <text x="275" y="54" text-anchor="middle" class="dg-text">REST API</text>
  <text x="275" y="72" text-anchor="middle" class="dg-sub">Spring Boot 4, Java 25</text>
  <rect x="390" y="30" width="150" height="56" rx="8" class="dg-box" />
  <text x="465" y="54" text-anchor="middle" class="dg-text">pod-indexing-jobs</text>
  <text x="465" y="72" text-anchor="middle" class="dg-sub">Kafka, key = podId</text>
  <rect x="580" y="30" width="140" height="56" rx="8" class="dg-box" />
  <text x="650" y="54" text-anchor="middle" class="dg-text">Job worker</text>
  <text x="650" y="72" text-anchor="middle" class="dg-sub">claim, stream items</text>
  <rect x="20" y="150" width="140" height="56" rx="8" class="dg-box" />
  <text x="90" y="174" text-anchor="middle" class="dg-text">Postgres</text>
  <text x="90" y="192" text-anchor="middle" class="dg-sub">pods, items, jobs</text>
  <rect x="200" y="150" width="150" height="56" rx="8" class="dg-box" />
  <text x="275" y="174" text-anchor="middle" class="dg-text">pgvector</text>
  <text x="275" y="192" text-anchor="middle" class="dg-sub">vector(384), HNSW</text>
  <rect x="390" y="150" width="150" height="56" rx="8" class="dg-box" />
  <text x="465" y="174" text-anchor="middle" class="dg-text">Item worker</text>
  <text x="465" y="192" text-anchor="middle" class="dg-sub">embed, upsert chunk</text>
  <rect x="580" y="150" width="140" height="56" rx="8" class="dg-box" />
  <text x="650" y="174" text-anchor="middle" class="dg-text">item-indexing-events</text>
  <text x="650" y="192" text-anchor="middle" class="dg-sub">Kafka, key = itemId</text>
  <rect x="20" y="270" width="140" height="56" rx="8" class="dg-box" />
  <text x="90" y="294" text-anchor="middle" class="dg-text">LLM</text>
  <text x="90" y="312" text-anchor="middle" class="dg-sub">Groq API or Ollama</text>
  <rect x="200" y="270" width="150" height="56" rx="8" class="dg-box" />
  <text x="275" y="294" text-anchor="middle" class="dg-text">Redis</text>
  <text x="275" y="312" text-anchor="middle" class="dg-sub">embedding cache</text>
  <rect x="390" y="270" width="150" height="56" rx="8" class="dg-box" />
  <text x="465" y="294" text-anchor="middle" class="dg-text">TEI server</text>
  <text x="465" y="312" text-anchor="middle" class="dg-sub">bge-small-en-v1.5</text>
  <rect x="580" y="270" width="140" height="56" rx="8" class="dg-box" />
  <text x="650" y="294" text-anchor="middle" class="dg-text">Dead-letter topic</text>
  <text x="650" y="312" text-anchor="middle" class="dg-sub">failed items</text>
  <line x1="160" y1="58" x2="198" y2="58" class="dg-line" marker-end="url(#social-distro-a1)" />
  <line x1="350" y1="58" x2="388" y2="58" class="dg-line-accent" marker-end="url(#social-distro-a2)" />
  <line x1="540" y1="58" x2="578" y2="58" class="dg-line-accent" marker-end="url(#social-distro-a2)" />
  <line x1="650" y1="86" x2="650" y2="148" class="dg-line-accent" marker-end="url(#social-distro-a2)" />
  <line x1="580" y1="178" x2="542" y2="178" class="dg-line-accent" marker-end="url(#social-distro-a2)" />
  <line x1="390" y1="178" x2="352" y2="178" class="dg-line-accent" marker-end="url(#social-distro-a2)" />
  <line x1="465" y1="206" x2="465" y2="268" class="dg-line" marker-end="url(#social-distro-a1)" />
  <line x1="390" y1="298" x2="352" y2="298" class="dg-line-dashed" marker-end="url(#social-distro-a1)" />
  <line x1="650" y1="206" x2="650" y2="268" class="dg-line-dashed" marker-end="url(#social-distro-a1)" />
  <line x1="205" y1="86" x2="125" y2="148" class="dg-line" marker-end="url(#social-distro-a1)" />
  <line x1="275" y1="86" x2="275" y2="148" class="dg-line" marker-end="url(#social-distro-a1)" />
  <line x1="222" y1="86" x2="142" y2="268" class="dg-line" marker-end="url(#social-distro-a1)" />
  <text x="282" y="124" class="dg-sub">query: kNN</text>
  <text x="20" y="356" class="dg-label">accent: indexing path · dashed: cache and failure paths</text>
</svg>
<p class="diagram-caption">Figure 1. Indexing fans out over two Kafka topics into pgvector; queries embed the question, search pgvector within the pod, and send the hits to the LLM.</p>
</div>

<p><strong>Write path.</strong> <code class="language-plaintext highlighter-rouge">POST /pods</code> and <code class="language-plaintext highlighter-rouge">POST /pods/{id}/data</code> store pods and text items in Postgres through JPA. The schema is
managed by Liquibase (<code class="language-plaintext highlighter-rouge">db/changelog</code>), and Hibernate runs with <code class="language-plaintext highlighter-rouge">ddl-auto: validate</code> so the entities have to match it.</p>

<p><strong>Indexing path.</strong> <code class="language-plaintext highlighter-rouge">POST /indexing/pods/{podId}</code> saves an <code class="language-plaintext highlighter-rouge">IndexingJob</code> as <code class="language-plaintext highlighter-rouge">PENDING</code>, publishes a <code class="language-plaintext highlighter-rouge">PodIndexingEvent</code> to
<code class="language-plaintext highlighter-rouge">pod-indexing-jobs</code> keyed by pod id, and returns <code class="language-plaintext highlighter-rouge">202 Accepted</code> with a job id. The job worker (3 listener threads)
claims the job with a conditional <code class="language-plaintext highlighter-rouge">UPDATE</code>, streams the pod’s items out of Postgres with a JDBC fetch size of 500, and
publishes one <code class="language-plaintext highlighter-rouge">ItemIndexingEvent</code> per item to <code class="language-plaintext highlighter-rouge">item-indexing-events</code>. The item workers (5 listener threads, 5 partitions)
call a Hugging Face Text Embeddings Inference (TEI) container running <code class="language-plaintext highlighter-rouge">BAAI/bge-small-en-v1.5</code>, and upsert a row into
<code class="language-plaintext highlighter-rouge">vector_chunks</code>, a <code class="language-plaintext highlighter-rouge">vector(384)</code> column with an HNSW index. A message that fails is sent to a dead-letter topic.
The client polls <code class="language-plaintext highlighter-rouge">GET /indexing/jobs/{jobId}</code>.</p>

<p><strong>Query path.</strong> <code class="language-plaintext highlighter-rouge">POST /pods/{podId}/query</code> embeds the question, runs <code class="language-plaintext highlighter-rouge">ORDER BY embedding &lt;-&gt; :q LIMIT 5</code> filtered by
<code class="language-plaintext highlighter-rouge">pod_id</code>, builds a context-plus-question prompt and sends it to the LLM client. In the current config that is
Llama 3.1 8B through Groq’s OpenAI-compatible API; earlier versions ran <code class="language-plaintext highlighter-rouge">phi3:mini</code> locally in Ollama.</p>

<p><strong>Frontend.</strong> A separate repo, <code class="language-plaintext highlighter-rouge">social-distro-ui</code>, is a small React 19 + Vite + TypeScript client using TanStack Query
and Zustand, with pages for pods, indexing (it polls job status) and querying.</p>

<h2 id="key-design-decisions">Key design decisions</h2>

<p><strong>1. Kafka fan-out instead of an in-process virtual-thread pool.</strong> The December 2025 version ran indexing inside the
API process: <code class="language-plaintext highlighter-rouge">Executors.newVirtualThreadPerTaskExecutor()</code>, items chunked into <code class="language-plaintext highlighter-rouge">CompletableFuture</code>s with <code class="language-plaintext highlighter-rouge">orTimeout</code> and
a retry counter. A test with 5,000 mocked items and 100 ms of simulated latency each finished under its 4-second
assertion, so virtual threads handled the I/O wait well. The problem was durability and isolation: a restart lost
in-flight jobs, and the work could only scale with the API pod. Moving to two Kafka topics made each item a
durable, retryable unit, and partitioning by pod id and item id spreads work across consumers. The cost is more moving
parts (ZooKeeper, a broker, serializer config) and a job status that is harder to define (see “What I’d do next”).</p>

<p><strong>2. Two-level fan-out (job, then items).</strong> The first topic carries one small event per job; the second carries one per
item. A single huge pod becomes thousands of independent item messages instead of one long-running message that pins
a consumer, which was the bottleneck I wrote down in the implementation plan (“one large pod blocks the entire worker
queue”). The trade-off is ordering: items of one pod are spread across partitions, so there is no “all items done”
signal without extra bookkeeping.</p>

<p><strong>3. Atomic job claim plus deterministic chunk ids, instead of locks.</strong> Kafka gives at-least-once delivery, so the same
message can arrive twice. The job worker only proceeds if <code class="language-plaintext highlighter-rouge">UPDATE ... SET status = RUNNING WHERE status = PENDING</code>
changes a row, so a redelivered job event is skipped. The item worker writes chunks with id <code class="language-plaintext highlighter-rouge">podId:itemId</code>, so a
redelivered item overwrites the same row rather than creating a duplicate. I also added <code class="language-plaintext highlighter-rouge">@Version</code> columns for optimistic
locking on pods and jobs. The alternative, a distributed lock or exactly-once Kafka transactions, would have been
heavier than the problem needed.</p>

<p><strong>4. pgvector in the existing Postgres instead of a separate vector database.</strong> Vectors sit next to the relational data,
so a pod-scoped search is one SQL query with a <code class="language-plaintext highlighter-rouge">WHERE pod_id = ?</code>, backups cover everything, and there is one less
service to run. The HNSW index (<code class="language-plaintext highlighter-rouge">m = 16, ef_construction = 64</code>, <code class="language-plaintext highlighter-rouge">vector_l2_ops</code>) matches the <code class="language-plaintext highlighter-rouge">&lt;-&gt;</code> operator the queries
use. The trade-off: filtering by pod on top of an approximate index can return fewer than <code class="language-plaintext highlighter-rouge">k</code> rows when a pod is a small
share of the table, which a dedicated store with native metadata filtering handles better.</p>

<p><strong>5. A small embedding server and a degraded answer path.</strong> I replaced Ollama for embeddings with TEI, which is built
only for embeddings, and swapped the vector column from 768 to 384 dimensions to match the smaller model. Embedding
calls go through a Resilience4j circuit breaker and are cached in Redis. If the embedding or vector search step throws,
the query service falls back to the pod’s aggregated text (<code class="language-plaintext highlighter-rouge">pod_indexes</code>) rather than returning an error. That keeps the
endpoint answering when the model server is down, at the cost of a less focused prompt.</p>

<h2 id="inside-the-code">Inside the code</h2>

<p>The job worker’s claim and fan-out (<code class="language-plaintext highlighter-rouge">IndexingWorker.java</code>). The conditional update is what makes duplicate delivery
harmless, and streaming the items keeps memory flat for large pods:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">boolean</span> <span class="n">claimed</span> <span class="o">=</span> <span class="n">jobRepository</span><span class="o">.</span><span class="na">updateStatusConditionally</span><span class="o">(</span>
        <span class="n">event</span><span class="o">.</span><span class="na">jobId</span><span class="o">(),</span> <span class="nc">JobStatus</span><span class="o">.</span><span class="na">PENDING</span><span class="o">,</span> <span class="nc">JobStatus</span><span class="o">.</span><span class="na">RUNNING</span><span class="o">);</span>
<span class="k">if</span> <span class="o">(!</span><span class="n">claimed</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">log</span><span class="o">.</span><span class="na">warn</span><span class="o">(</span><span class="s">"Job {} already claimed by another worker, skipping."</span><span class="o">,</span>
            <span class="n">event</span><span class="o">.</span><span class="na">jobId</span><span class="o">());</span>
    <span class="k">return</span><span class="o">;</span>
<span class="o">}</span>
<span class="c1">// …</span>
<span class="n">podRepository</span><span class="o">.</span><span class="na">streamItems</span><span class="o">(</span><span class="n">event</span><span class="o">.</span><span class="na">podId</span><span class="o">(),</span> <span class="n">item</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="nc">ItemIndexingEvent</span> <span class="n">itemEvent</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ItemIndexingEvent</span><span class="o">(</span><span class="n">event</span><span class="o">.</span><span class="na">podId</span><span class="o">(),</span>
            <span class="n">item</span><span class="o">.</span><span class="na">getId</span><span class="o">(),</span> <span class="n">item</span><span class="o">.</span><span class="na">getContent</span><span class="o">(),</span> <span class="n">llmProperties</span><span class="o">.</span><span class="na">getEmbeddingModel</span><span class="o">());</span>
    <span class="c1">// Use item.getId() as key for partitioning</span>
    <span class="n">kafkaTemplate</span><span class="o">.</span><span class="na">send</span><span class="o">(</span><span class="s">"item-indexing-events"</span><span class="o">,</span> <span class="n">item</span><span class="o">.</span><span class="na">getId</span><span class="o">(),</span> <span class="n">itemEvent</span><span class="o">);</span>
    <span class="n">combinedText</span><span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">item</span><span class="o">.</span><span class="na">getContent</span><span class="o">()).</span><span class="na">append</span><span class="o">(</span><span class="s">"\n"</span><span class="o">);</span>
    <span class="n">count</span><span class="o">.</span><span class="na">incrementAndGet</span><span class="o">();</span>
<span class="o">});</span>
<span class="n">podIndexRepository</span><span class="o">.</span><span class="na">save</span><span class="o">(</span>
        <span class="k">new</span> <span class="nf">PodIndex</span><span class="o">(</span><span class="n">event</span><span class="o">.</span><span class="na">podId</span><span class="o">(),</span> <span class="n">combinedText</span><span class="o">.</span><span class="na">toString</span><span class="o">()));</span>
<span class="n">jobRepository</span><span class="o">.</span><span class="na">markAsCompleted</span><span class="o">(</span><span class="n">event</span><span class="o">.</span><span class="na">jobId</span><span class="o">());</span>
</code></pre></div></div>

<p>The query path with its fallback (<code class="language-plaintext highlighter-rouge">QueryService.java</code>). Retrieval is scoped to one pod, and a failure in the vector path
degrades to the aggregated text instead of failing the request:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">try</span> <span class="o">{</span>
    <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Double</span><span class="o">&gt;</span> <span class="n">questionEmbedding</span> <span class="o">=</span>
            <span class="n">embeddingClient</span><span class="o">.</span><span class="na">generateEmbedding</span><span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">question</span><span class="o">());</span>
    <span class="kt">float</span><span class="o">[]</span> <span class="n">embeddingArray</span> <span class="o">=</span> <span class="n">toFloatArray</span><span class="o">(</span><span class="n">questionEmbedding</span><span class="o">);</span>
    <span class="nc">List</span><span class="o">&lt;</span><span class="nc">VectorChunkEntity</span><span class="o">&gt;</span> <span class="n">similarChunks</span> <span class="o">=</span>
            <span class="n">vectorStore</span><span class="o">.</span><span class="na">findSimilarByPodId</span><span class="o">(</span><span class="n">podId</span><span class="o">,</span> <span class="n">embeddingArray</span><span class="o">,</span> <span class="no">TOP_K_CHUNKS</span><span class="o">);</span>
    <span class="n">context</span> <span class="o">=</span> <span class="n">buildContextFromChunks</span><span class="o">(</span><span class="n">similarChunks</span><span class="o">);</span>
    <span class="n">usedItemIds</span> <span class="o">=</span> <span class="n">similarChunks</span><span class="o">.</span><span class="na">stream</span><span class="o">()</span>
            <span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="nl">VectorChunkEntity:</span><span class="o">:</span><span class="n">getId</span><span class="o">).</span><span class="na">toArray</span><span class="o">(</span><span class="nc">String</span><span class="o">[]::</span><span class="k">new</span><span class="o">);</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">log</span><span class="o">.</span><span class="na">warn</span><span class="o">(</span><span class="s">"RAG search failed, falling back to PodIndex. Error: {}"</span><span class="o">,</span>
            <span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">());</span>
    <span class="nc">PodIndex</span> <span class="n">podIndex</span> <span class="o">=</span> <span class="n">podIndexRepository</span><span class="o">.</span><span class="na">findByPodId</span><span class="o">(</span><span class="n">podId</span><span class="o">);</span>
    <span class="n">context</span> <span class="o">=</span> <span class="n">podIndex</span> <span class="o">!=</span> <span class="kc">null</span> <span class="o">?</span> <span class="n">podIndex</span><span class="o">.</span><span class="na">getCombinedText</span><span class="o">()</span> <span class="o">:</span> <span class="s">""</span><span class="o">;</span>
    <span class="n">usedItemIds</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">String</span><span class="o">[]</span> <span class="o">{</span> <span class="s">"fallback:pod-index"</span> <span class="o">};</span>
<span class="o">}</span>
</code></pre></div></div>

<h2 id="running-it">Running it</h2>

<p>Everything runs from one Compose file: Postgres with pgvector, Redis, TEI, ZooKeeper, Kafka, Prometheus, Grafana,
Zipkin and the app, each with a health check and CPU/memory limits. The app image is a three-stage Dockerfile
(Maven build, Spring Boot layer extraction, non-root JRE 25 Alpine runtime).</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># .env: POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB, GROQ_API_KEY</span>
docker compose up <span class="nt">-d</span> <span class="nt">--build</span>
<span class="c"># create a pod, add 50 items, start indexing, poll the job</span>
python stress_test.py
<span class="c"># then: POST /pods/{podId}/query  {"question": "..."}</span>
</code></pre></div></div>

<h2 id="what-id-do-next">What I’d do next</h2>

<ul>
  <li><strong>Finish or revert the last refactor.</strong> The latest commit on <code class="language-plaintext highlighter-rouge">main</code> (July 2026) started moving to LangChain4j
(<code class="language-plaintext highlighter-rouge">IngestionPipeline</code>, <code class="language-plaintext highlighter-rouge">HybridSearchService</code>, <code class="language-plaintext highlighter-rouge">AiPlatformConfig</code>). Those classes are not wired to any endpoint yet and
use placeholder text and config, and the same commit removed the Kafka producer/consumer config that the workers
depend on (JSON serializer, manual acks). The design above is the January 2026 version (<code class="language-plaintext highlighter-rouge">758fe98</code>). I’d restore that
config first, then bring LangChain4j in behind the existing <code class="language-plaintext highlighter-rouge">EmbeddingClient</code> and <code class="language-plaintext highlighter-rouge">VectorStore</code> interfaces.</li>
  <li><strong>Fix the float conversion in <code class="language-plaintext highlighter-rouge">ItemIndexingWorker</code>.</strong> Its <code class="language-plaintext highlighter-rouge">toFloatArray</code> collector writes every value to index 0, so
stored vectors are wrong. <code class="language-plaintext highlighter-rouge">QueryService</code> has a correct loop; both should share one helper with a unit test.</li>
  <li><strong>Make job status mean “indexed”.</strong> A job is marked <code class="language-plaintext highlighter-rouge">COMPLETED</code> once the item events are published, not once they
are embedded. I’d track an expected/processed item count per job and complete it from the item worker side.</li>
  <li><strong>Make retries real.</strong> <code class="language-plaintext highlighter-rouge">processWithRetry</code> is called from inside the same bean, so Spring’s proxies never apply
<code class="language-plaintext highlighter-rouge">@Retry</code> or <code class="language-plaintext highlighter-rouge">@Transactional</code> to it. It should move to a separate bean. The dead-letter topic also has no consumer or
replay tool yet.</li>
  <li><strong>Bring tests back and add CI.</strong> An early stress test was removed during the Kafka migration and there are no tests
now. I’d add Testcontainers tests for Postgres+pgvector and Kafka, and a GitHub Actions build.</li>
  <li><strong>Measure before claiming.</strong> There is a latency script (<code class="language-plaintext highlighter-rouge">latency_test.ps1</code>) but no recorded results. I’d run it at a
few data sizes and publish the numbers, including the effect of the pod filter on HNSW recall.</li>
</ul>

<h2 id="skills-this-shows">Skills this shows</h2>

<ul>
  <li><strong>Backend (Java/Spring):</strong> Spring Boot 4 on Java 25, a ports-and-adapters layout (domain <code class="language-plaintext highlighter-rouge">VectorStore</code> /
repository interfaces, JPA adapters, MapStruct mappers), Liquibase migrations, optimistic locking, streamed JPA queries.</li>
  <li><strong>Distributed systems:</strong> two-stage Kafka fan-out keyed for partitioning, manual acknowledgements, idempotent consumers
(conditional status update, deterministic ids), a dead-letter topic.</li>
  <li><strong>AI / RAG engineering:</strong> embedding server selection (TEI, 384-dim bge-small), pgvector schema and HNSW index, scoped
kNN retrieval, prompt assembly, pluggable LLM providers (Groq/OpenAI-compatible, Ollama, a fake client for tests).</li>
  <li><strong>Resilience:</strong> Resilience4j circuit breaker on the embedding client, retry config, fallback to aggregated text.</li>
  <li><strong>Platform / SRE:</strong> multi-stage non-root Docker image, a nine-service Compose stack with health checks and resource
limits, Micrometer counters and timers, Zipkin tracing, Prometheus and Grafana containers.</li>
  <li><strong>Concurrency:</strong> an earlier virtual-thread executor with <code class="language-plaintext highlighter-rouge">CompletableFuture</code> timeouts and retries, and the reasons I
moved past it.</li>
</ul>]]></content><author><name>Raghavendra Singh Chauhan</name><email>raghavendra.swe666@gmail.com</email></author><category term="java" /><category term="spring-boot" /><category term="kafka" /><category term="pgvector" /><category term="rag" /><category term="docker" /><summary type="html"><![CDATA[A Spring Boot service that indexes per-user text collections through a two-stage Kafka fan-out into pgvector and answers questions with RAG.]]></summary></entry></feed>