Adeli Chat Sends an Instagram DM When Someone Comments a Keyword. The Hard Part Is Doing It Exactly Once.

A free, self-hosted alternative to ManyChat that uses Postgres constraints as a state machine, treats webhook redelivery as the enemy, and ships with a spec-driven codebase most demos never bother to write.

9 min read • View on GitHub • More from kingscrosslabs

A wide editorial illustration of a stylized Instagram comment feed drawn in black ink on pure white. One comment bubble contains the word GUIDE, and a single taut thread runs diagonally from it across a faint hand-lettered boundary line toward a small closed envelope with a button on its face. The image shows how a single public comment becomes a single private DM, with all other comments left unthreaded.
One comment, one thread, one private destination. The product concept in a single diagonal.
Key Takeaways

What a comment-to-DM automation actually is

You have seen these in the wild. A creator posts a carousel and writes "comment GUIDE and I'll send you the link" in the caption. A stranger comments. Seconds later a public reply appears under their comment, and a private message shows up in their inbox with a button. They tap it. The link arrives. Most people never think about what happens in between, which is exactly where this project gets interesting.

The full funnel in Adeli Chat runs in five steps:

  1. A comment arrives on a post, delivered as a webhook event from the Adeli API.
  2. The app matches the comment text against the live automation for that specific post.
  3. It posts a public reply under the comment, picked at random from a list of variants.
  4. It opens a private DM containing a single button, whose payload is the run ID.
  5. When the user taps the button, a second webhook fires and the final DM with the link goes out.

That is the whole product. It is also a distributed-systems problem wearing a marketing hat, and the code knows it.

The hard part is not the DM. It is the exactly-once guarantee.

Three failure modes make the simple version of this funnel unreliable. Meta redelivers webhooks when it does not get a timely acknowledgement, so the same comment event can arrive twice. Users tap buttons twice, because users tap buttons twice. And responses get dropped between the API call and the client, so the app cannot always tell whether a step succeeded.

Any of those produces the same embarrassing outcome: the same person gets the same DM more than once, or the same comment gets two public replies. The interesting code in Adeli Chat is not the Instagram integration. Adeli handles that. The interesting code is the part that makes sure one comment produces one DM, no matter how many times the network tries to deliver it.

A close-up editorial illustration in black ink on pure white. A single finger presses a small rounded rectangular button, and behind it a database row is drawn in crosshatching with a small padlock hasp clicking shut over it. A second ghosted finger, lighter and stippled, approaches the same button from the opposite side and finds the padlock already closed. The image is the visual metaphor for a compare-and-swap, where only one tap can claim the transition.
Two taps, one winner. The compare-and-swap is the intellectual core of the whole app.

Two Postgres primitives do the work of a workflow engine

The first trick is dedupe by insert. When a comment event arrives, the handler tries to create a run row for it and asks Postgres to do nothing on a conflict:

const [run] = await db().insert(schema.runs)
  .values({ ... })
  .onConflictDoNothing()
  .returning({ ... });

if (!run) return; // already handled

If nothing comes back, the event was already handled and the function returns. The dedupe is not application logic checking a flag. It is a unique constraint in the database, which means it holds even when two webhook deliveries land at the same instant. The inline comment says it plainly:

The second trick is the button tap. The postback button in the opening DM carries the run ID as its payload, which turns a user interface interaction into a database compare-and-swap:

const [run] = await db().update(schema.runs)
  .set({ state: "final_sending", tappedAt: now, updatedAt: now })
  .where(and(
    eq(schema.runs.id, event.data.payload),
    eq(schema.runs.state, "opening_sent"),
  ))
  .returning({ ... });

if (!run) return; // someone already claimed this tap

The WHERE state = 'opening_sent' clause is the whole guarantee. Only one delivery of a tap can move the run out of that state. Every other delivery gets zero rows and exits silently. A duplicate postback can never send a second final DM, because there is no second transition to claim.

That is the trick. The run ID becomes the button payload, and a button tap becomes a single-row update with a guard. One line of code, one guarantee.

The full lifecycle of a single run, with both guard moments rendered as gates. Redeliver the webhook or tap again and watch the guard fire.

Acknowledge fast, process later

The webhook route is the system's only entry point, and it is written like the authors expect it to fail. It reads the raw request body first, before any parsing, then verifies the signature against those exact bytes. Parsing JSON before verifying would change the bytes and break the signature, so the order matters.

After verification it parses the event, hands it to after() from next/server, and returns a 200 immediately. The handler runs after the response is sent. This keeps Adeli from waiting on Meta API calls that can take seconds, which is the same reason a slow acknowledgement triggers the redeliveries the dedupe exists to absorb. Errors inside the handler are caught and logged, since they cannot reach the caller anyway.

One small detail is worth noticing. If the install has no webhook secret stored, the route returns 503 rather than 401. That tells Adeli "not ready" instead of "bad request," which is the difference between retrying and giving up.

A demo that ships like production

The exactly-once machinery would be enough for a weekend demo. The rest of the repo is where it stops being one. The code comments cite the spec directly, referencing PRD sections and decision IDs like D2 and D3, so every non-obvious choice traces back to a written reason.

None of this is required to make the funnel work once. All of it is required to make the funnel work the ten thousandth time, which is the actual job.

Free, self-hosted, and honest about what it is

Adeli Chat is not trying to out-feature ManyChat. It calls itself a demo of the Adeli API, and that framing is accurate. What it offers is a different trade: no subscription, your own database, and a codebase you can read. What it costs is setup, because you still need an Adeli API key and a running Postgres or PGlite instance.

DimensionManyChatAdeli ChatRolling your own
CostPaid tiersFree, MIT licensedFree plus your time
HostingVendor-hostedSelf-hosted (a laptop works)You
Instagram integrationBundledVia the Adeli APIYou handle Meta review, OAuth, and tokens
Data locationVendorYour Postgres or PGliteYour choice
Exactly-once guaranteesNot documented hereExplicit in the codeYou build it
AudienceMarketers, no codeDevelopers and small creatorsDevelopers

The honest read: if you want a marketing tool with a dashboard and support, pay for ManyChat. If you want to understand how a comment-to-DM funnel survives the network, read this repo. The two Postgres tricks are worth the read on their own, and they port to any system where a user action has to happen exactly once.