Lesson 4 of 5 · 9 min
Send events reliably
Report events to a brain from your backend with retries and increasing backoff, handle the 400, 404 and 409 codes, and read the status of each run.
An event tells the brain that something happened in your systems (a new lead, a payment received) so it runs its skills in Autonomous Mode. Sending it is a single POST; sending it well means retrying what's worth retrying, not retrying what isn't, and knowing what happened with each run.
What you'll achieve
- Send events with retries and increasing backoff only when the error is temporary.
- Handle each
/eventosresponse code with a clear decision. - Read
ejecuciones[].estadoand avoid duplicate work.
The call
curl -s https://mcp.zunous.com/api/v1/acme/cobranza/eventos \
-H "Authorization: Bearer $ZUNOUS_LLAVE" -H "Content-Type: application/json" \
-d '{"evento": "erp.pago_recibido", "datos": {"id_pago": "PG-88120", "cliente": "Luis Gómez", "valor": 1200000, "factura": "FV-1023"}}'| Field | Rule |
|---|---|
evento | Lowercase letters, numbers, _ and periods, up to 80 characters. By convention dominio.evento (domain.event) |
datos | Any JSON with what the brain needs. It reads it as information, never as instructions, up to 20,000 characters |
The full body can't exceed 100,000 characters. If it does, the response is 413.
If the response is 202, the event was accepted:
{
"aceptado": true,
"ejecuciones": [
{ "id": "7b1e…", "habilidad": "conciliar_pago", "estado": "pendiente", "error": null }
]
}Each skill that listens for the event is queued as a run.
Decide what to retry
| Code | What it means | What to do |
|---|---|---|
202 | Accepted | Check ejecuciones[].estado |
400 | The event name isn't in a valid format, or the JSON is invalid | Don't retry: it's a bug in your code |
401 | The key doesn't match that organization and brain | Don't retry: raise an alert and ask for the current key |
404 | No trigger on this brain listens for that event | Don't retry: the trigger still has to be created in the Console |
409 | The brain's Autonomous Mode is off | Don't retry right away: store the event and notify the admin |
413 | The body exceeds 100,000 characters | Don't retry: send less data |
5xx or network down | Temporary failure | Retry with increasing backoff: 1 s, 2 s, 4 s |
The 404 is checked before the 409: if you get a 409, the trigger does exist and Autonomous Mode just needs to be turned on.
A sender with retries
const BASE = "https://mcp.zunous.com/api/v1/acme/cobranza";
const espera = (ms) => new Promise((r) => setTimeout(r, ms));
export class ErrorZunous extends Error {
constructor(status, mensaje) {
super(`Zunous ${status}: ${mensaje}`);
this.status = status;
}
}
export async function avisarEvento(evento, datos, intentos = 4) {
for (let i = 1; i <= intentos; i++) {
let respuesta;
try {
respuesta = await fetch(`${BASE}/eventos`, {
method: "POST",
headers: { Authorization: `Bearer ${process.env.ZUNOUS_LLAVE}`, "Content-Type": "application/json" },
body: JSON.stringify({ evento, datos }),
signal: AbortSignal.timeout(15_000),
});
} catch (err) {
if (i === intentos) throw err; // network down or timeout on the last attempt
await espera(1000 * 2 ** (i - 1) + Math.random() * 250);
continue;
}
if (respuesta.status === 202) return revisar(await respuesta.json());
const { error } = await respuesta.json().catch(() => ({ error: respuesta.statusText }));
if (respuesta.status >= 500 && i < intentos) {
await espera(1000 * 2 ** (i - 1) + Math.random() * 250);
continue;
}
throw new ErrorZunous(respuesta.status, error);
}
}
function revisar({ ejecuciones }) {
for (const e of ejecuciones) {
if (e.estado === "omitida") console.warn(`${e.habilidad} skipped: ${e.error}`);
}
return ejecuciones;
}And the caller decides based on the code:
try {
await avisarEvento("erp.pago_recibido", { id_pago: "PG-88120", cliente: "Luis Gómez", valor: 1200000, factura: "FV-1023" });
} catch (err) {
if (err.status === 409) await guardarParaDespues(err); // Autonomous Mode off: resend when it's turned on
else if (err.status === 404 || err.status === 401) await alertarAlEquipo(err); // missing configuration
else throw err; // 400, 413 or a persistent failure: an error that needs fixing
}guardarParaDespues and alertarAlEquipo are yours to write: a pending table, a message to the team's channel, whatever your operation uses.
Read the status and avoid duplicates
In the 202 response, each run comes with one of two statuses:
pendiente(pending): it's queued and the brain will work on it.omitida(skipped): it won't run because the brain reached its daily cap (50 runs by default). Theerrorfield explains it, for example «Se alcanzó el tope de 50 ejecuciones por día» ("The cap of 50 runs per day was reached"). The response is still202.
What happens next (what the brain looked up, what it did, what it left for approval) is visible in the Console, in the brain's Action log. Today the REST API has no route to look up a run by its id: store the id in your records to match it against the log.
The details on events, triggers and caps are in Events and triggers and Limits and plans.
Practice
Fintech Ahorro Fácil, in Mexico City, wants the Collections Brain to reconcile every payment that reaches its payment gateway:
- Implement
avisarEventoand senderp.pago_recibidowithid_pago, customer, amount and invoice. - Swap the key for an invalid one and confirm there are no retries (
401throws immediately). - Send the
erp.pago_reversadoevent, which has no trigger, and confirm the404. Then ask the admin to create your own trigger and repeat. - Ask them to turn off Autonomous Mode on a test brain, send an event and verify that it ends up in
guardarParaDespues. - Record each run's
idin your logs and look it up in the Console's Action log.
Check what you learned
1. You get a 409 when reporting an event. Do you retry in a second?
2. The response was 202, but one run has estado: "omitida". What happened?
3. Why should you send the record's ID in datos?