How I generate social posts with LangGraph in Node.js
Gemini in Sosifie's Node.js backend: a LangGraph loop that never looped, schema-constrained JSON, overlapping cron jobs and a crawler that had to move out.
Sosifie's backend has a LangGraph graph with a rewrite loop in it, and that loop has never gone around twice. The AI side is a smart compose button, cron jobs posting as a bot account, and a trend crawler. The stack is Express, Prisma on Postgres, node-cron and Google's Gemini JavaScript SDK. The lockfile has @langchain/langgraph 1.4.4, @langchain/core 1.2.0, @google/generative-ai 0.24.1 and node-cron 3.0.3.
The composer graph that never looped
Smart compose has five modes, from fixing grammar to expanding a short note into a full post. The output is Markdown, and the first line has to be an H1 because the editor uses it as the title. One Gemini call rewrote fine but often broke the format. It dropped the heading or wrapped the post in quotes, and once added an inspirational quote nobody asked for.
So I added a refiner node after the writer node, with a conditional edge back to the writer or to the end, on a StateGraph with a counter capped at two rounds. But the refiner always set its critique to "OK", so every run went writer, refiner, done, which is a two-step pipeline wrapped in a graph. A real review loop needs a reviewer that returns a verdict the router can trust:
import { Annotation, StateGraph, START, END } from '@langchain/langgraph'
const PostState = Annotation.Root({
input: Annotation<string>(),
mode: Annotation<string>(),
draft: Annotation<string>(),
verdict: Annotation<'pass' | 'revise'>(),
notes: Annotation<string>(),
attempts: Annotation<number>(),
})
export const composeGraph = new StateGraph(PostState)
.addNode('write', async (s) => ({
draft: await writeDraft(s.input, s.mode, s.notes),
attempts: s.attempts + 1,
}))
.addNode('review', async (s) => reviewDraft(s.draft, s.mode)) // { verdict, notes }
.addEdge(START, 'write')
.addEdge('write', 'review')
.addConditionalEdges('review', (s) =>
s.verdict === 'pass' || s.attempts >= 2 ? END : 'write',
)
.compile()
// const { draft } = await composeGraph.invoke({ input, mode, notes: '', attempts: 0 })
reviewDraft should use structured output (next section) so verdict can only be one of the two strings. Annotation.Root still works in 1.4, though newer LangGraph docs use StateSchema with Zod.
The endpoint the editor actually calls doesn't touch the graph: it streams one call (generateContentStream) into the Express response. I think that's right, because behind a button two passes means staring at an empty box. The graph fits background work. Streaming through nginx needs the X-Accel-Buffering: no header, because otherwise nginx may buffer the whole response.
Forcing JSON with a response schema
The prompt includes a rule against wrapping the output in quotes, and there's still a regex that strips surrounding quotes. JSON went the same way. Gemini sometimes wraps it in a code fence. The parser handles that by taking everything from the first { to the last } and running JSON.parse.
Gemini can enforce this with responseMimeType: 'application/json' plus a responseSchema. Google's structured output docs still say to validate values in your app, so Zod sits behind it:
import { GoogleGenerativeAI, SchemaType } from '@google/generative-ai'
import { z } from 'zod'
const CATEGORIES = ['art', 'tech', 'fashion', 'music', 'lifestyle', 'food'] as const
const Trend = z.object({
title: z.string().min(1).max(120), category: z.enum(CATEGORIES),
prompts: z.array(z.string().min(1)).min(1).max(3),
})
const str = { type: SchemaType.STRING } as const
const model = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!).getGenerativeModel({
model: process.env.GEMINI_MODEL!,
generationConfig: {
responseMimeType: 'application/json',
responseSchema: {
type: SchemaType.OBJECT,
properties: {
title: str,
category: { type: SchemaType.STRING, format: 'enum', enum: [...CATEGORIES] },
prompts: { type: SchemaType.ARRAY, items: str },
},
required: ['title', 'category', 'prompts'],
},
},
})
export async function classifyTrend(keyword: string) {
const res = await model.generateContent(`Trend keyword: ${JSON.stringify(keyword)}`)
const parsed = Trend.safeParse(JSON.parse(res.response.text()))
return parsed.success ? parsed.data : null // log parsed.error, never save junk
}
The current code only checks that title and category have values, so invented categories go straight into the database. An enum in both the schema and Zod stops that. The Markdown the model returns shows up in other people's feeds, so sanitize it before rendering.
@google/generative-ai is deprecated in favor of @google/genai, so check field names against current docs. On LangChain, chat models have withStructuredOutput(zodSchema) and you skip the hand-written schema.
Retrying 429s with jitter, counting calls instead of guessing cost
Gemini limits requests per minute, tokens per minute and requests per day, per project, so adding API keys doesn't help. The daily quota resets at midnight Pacific time.
The retry wrapper waits 4, 8, then 16 seconds on a 429, but still sleeps 16 seconds after the last failure before throwing. Every job also backs off on the same schedule, so parallel runs retry together. With jitter and no final sleep:
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
function isRetryable(err: unknown) {
const status = (err as { status?: number })?.status
return status === 429 || status === 503
}
export async function withBackoff<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {
for (let i = 0; ; i++) {
try {
return await fn()
} catch (err) {
if (!isRetryable(err) || i === attempts - 1) throw err // no sleep before giving up
const base = 2000 * 2 ** i
await sleep(base + Math.random() * base)
}
}
}
For cost, I count calls. The trend job makes at most ten calls every six hours and the news job at most four an hour, small next to a button any signed-in user can keep pressing. Per-user rate limiting on the AI route matters more, and for real numbers, log each response's usageMetadata.
Cron jobs that overlap and run on startup
The news job runs hourly, rewriting unseen items from two random RSS sources with Gemini and posting them as the bot account. The trend job runs every six hours. (The oldest job posted lorem ipsum as a random user. I unhooked it from startup, and demo data now comes from a seed.)
Both also run once at startup, so every deploy, restart or nodemon reload triggers a crawl, and each extra instance runs its own scheduler. node-cron 3 doesn't wait for an async callback before the next tick, so a slow run can overlap the next one (version 4 has noOverlap). Without timezone, schedules follow server time, which in a container is usually UTC.
Both jobs "find first, create if missing" on a column with no unique constraint, so two overlapping runs can both insert. Skip overlapping runs and put a unique constraint on the column:
import cron from 'node-cron'
import { Prisma } from '@prisma/client'
let running = false
cron.schedule('0 */6 * * *', async () => {
if (running) return // node-cron 3 won't skip an overlapping run for you
running = true
try {
await runTrendJob()
} catch (err) {
console.error('[trends] run failed', err)
} finally {
running = false
}
}, { timezone: 'Asia/Ho_Chi_Minh' })
// originalTitle is @unique in schema.prisma
async function saveTrend(data: Prisma.TrendingTopicCreateInput) {
try {
await prisma.trendingTopic.create({ data })
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') return
throw err
}
}
The running flag only works within one process; with several instances you need a Postgres advisory lock, or one worker running the jobs.
Moving the crawler out
The trend crawler started with Google Trends' RSS for Vietnam and Reddit's r/all as JSON. Reddit returned 403, I faked a Chrome User-Agent "to bypass 403", then dropped Reddit and used the US Google Trends RSS as the global source. Faking Chrome was wrong. Reddit wants scripts to use its OAuth API with a registered app. From what I've read, unauthenticated requests from server IPs get blocked whatever the headers say. RSS is meant to be polled but only gives titles, so Gemini translates and classifies them.
Then I removed 138 lines from the backend and moved the crawler to its own repo, a small Node service writing to the same Postgres through Prisma. No incident forced the move. The API shuts down on any unhandled promise rejection, so a sloppy background job can take the API down with it. A separate worker can restart on its own and run as exactly one copy.
In exchange, the crawler keeps a copy of the backend's Prisma schema, which will drift. The Gemini quota is still shared per project, and the RSS news job is still part of the API and should move too. The trend score column is currently Math.random(), a placeholder that looks like real data. Replace it with a real signal or drop it before someone sorts by it.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.