Disclosure up front: I built this and I sell it as a paid template pack. I built it with AI assistance, and I reviewed and test-ran every workflow in n8n myself.
Sharing the pattern behind the invoice workflow, because “send the reminder for stage N exactly once” was the fiddly part.
How it works
- A Schedule trigger runs on weekday mornings and reads an invoices sheet in Google Sheets.
- A Code node works out each unpaid row’s stage from its due date: 3 days before, then 1, 7 and 14 days after.
- It compares that stage with the
last_stage_sent column in the sheet. If the row is already at that stage, or is marked paid, it gets skipped. That check is what stops duplicate emails when the workflow reruns.
- It sends through Gmail, then writes the new stage back to the row. The final stage also posts a Slack alert (Slack is optional).
A gotcha I hit: my log date used UTC, so evening runs in US Eastern wrote tomorrow’s date. The fix was to format dates in a timezone set once in a Settings node instead of relying on the server default.
How I tested it: I imported all 4 workflows into n8n 2.44.6 and ran them with mock sheet data and the sends swapped for No-Op nodes. All 4 runs passed. I have not tested against live Google, Gmail or Slack accounts yet, so if you try the pattern, do a self-addressed test first.
The same “sheet + Settings node + Code node” layout drives 3 other workflows: renewal and compliance deadline digests, stale-lead follow-ups, and an “unanswered email” digest that skips Gmail’s Promotions/Social/Updates/Forums tabs and no-reply senders. Everything is plain JavaScript, with no AI service or paid API keys.
Happy to paste the stage-calculation Code node here if it’s useful.
Feedback on the dedupe approach is very welcome. Is there a cleaner way than a stage column?
The full pack (4 workflows, sample sheets, a PDF setup guide) is my own product, $29: Back-Office Autopilot: 4 n8n Workflows for Small Business (Invoices, Deadlines, Leads, Inbox)
1 Like
I like the stage column because someone can understand it directly from the sheet. The gap I’d test is Gmail accepting the reminder but the last_stage_sent update failing. The next run could then send the same stage again.
I’d keep the stage, but add an attempt status or send record so an uncertain result goes to review instead of being resent automatically. I’d also recheck paid just before sending, in case payment arrived after the initial sheet read.
1 Like
Good catch, that’s a real gap. If Gmail sends and the sheet write fails, the next run sees the old stage and sends again. Here’s how I’d close it with two extra columns, pending_stage and pending_at:
- Before the Gmail node, write
pending_stage = stage and pending_at = now to the row.
- Send.
- On success, write
last_stage_sent = stage and clear pending_stage.
Then the Code node treats a leftover pending value as “uncertain” and routes it to review instead of resending:
const settings = $('Settings').first().json;
return $input.all().map(({ json: row }) => {
const stage = row.computed_stage; // from the due-date step
const last = Number(row.last_stage_sent || 0);
const pending = Number(row.pending_stage || 0);
let action = 'send';
if (String(row.paid).toLowerCase() === 'yes' || stage <= last) action = 'skip';
else if (pending && pending > last) action = 'review'; // send may have gone out, sheet update didn't land
return { json: { ...row, stage, action } };
});
A Switch on action sends review rows to a Slack or email note for a human to check the Sent folder.
For the late payment, I’d add a Google Sheets “Get row” by invoice ID right before the Gmail node and an IF on paid, so it reads the live value instead of the morning snapshot. It costs one extra read per send, which is fine at small-business volumes.
Thanks, I’m adding both to the pattern.
1 Like
Really nice pattern — the stage column doubling as a human-readable audit trail right in the sheet is a great touch. One edge case worth guarding in the Code node: when the Schedule trigger lands on a weekend, a “3 days before” stage can drift past the due date before the reminder ever goes out, so anchoring stage boundaries to business days made a similar workflow I built much more predictable. I’d also keep a small append-only log tab of every send attempt, failures included — when a client asks “did you send it?” you get a definitive answer instead of digging through execution history. And the pending_stage fix for failed writes is the right call; a leftover pending row is exactly the kind of thing that should route to review rather than silently skipping. Solid, testable design overall.
1 Like
The stage-column approach is simple and practical. One edge case worth considering is a partial failure: Gmail successfully sends the reminder, but the Google Sheets update fails. On the next scheduled run, the same reminder may be sent again because last_stage_sent still has the old value.
For stronger reliability, I’d consider tracking each reminder with a stable key such as invoice_id + reminder_stage, and recording its status (pending, sent, or failed) in a persistent store with a uniqueness constraint.
There’s still an important limitation: if the email provider accepts the message but the workflow times out before recording success, the system may not know whether the email was sent. A status column alone cannot guarantee exactly-once email delivery.
How are you planning to handle that send-success / sheet-update-failure scenario?
1 Like
Good call on weekends. Two things fix it in the Code node: count business days instead of calendar days, and pick the highest stage whose threshold has already passed, so a reminder that would have fired on a Saturday goes out on Monday instead of being skipped. It also means a “due soon” note never goes out after the due date, because by then the row is already at the first overdue stage.
// business days until due (negative = overdue); dates normalized to midnight in the Settings timezone
function bizDaysUntil(due, today) {
let n = 0;
const d = new Date(today);
const step = due > today ? 1 : -1;
while ((step > 0 && d < due) || (step < 0 && d > due)) {
d.setDate(d.getDate() + step);
if (d.getDay() % 6 !== 0) n += step; // skip Sat (6) and Sun (0)
}
return n;
}
const days = bizDaysUntil(new Date(row.due_date), today);
const stage = days <= -14 ? 4 : days <= -7 ? 3 : days <= -1 ? 2 : days <= 3 ? 1 : 0;
The existing stage <= last_stage_sent check still does the dedupe, so jumping from 0 straight to 2 is fine.
Agreed on the log tab too. An Append row to a “Send log” tab after the Gmail node, with invoice_id, stage, status, timestamp and the Gmail message id it returns, answers “did you send it?” in seconds. If you set the Gmail node’s On Error setting to “Continue (using error output)”, you can log the failures to the same tab.
1 Like
Agreed, exactly-once isn’t possible with email, so I aim for at-most-once plus review. The pending_stage write from my reply above happens before the send, so the timeout case you describe leaves a pending row behind, and the next run routes it to review instead of resending. The worst case is a late reminder that a person checks, never a double send.
To make most of those reviews automatic, put a unique tag in the subject, like INV-1042 R2, and have the review branch ask Gmail before deciding:
- Gmail node, Get Many messages, Search filter:
in:sent subject:"INV-1042 R2" newer_than:7d
- Found: write
last_stage_sent and clear pending_stage.
- Not found: clear
pending_stage and let the next run send it.
On the uniqueness constraint, Sheets has none, so at higher volume I’d move the send log to Postgres with a unique index on (invoice_id, stage) and insert the row before sending. A conflict on insert means skip.
1 Like
Thanks for explaining the pending-stage and review approach. I agree that routing uncertain outcomes to review is safer than blindly retrying and risking duplicate reminders.
One caveat with the Gmail reconciliation step: a message not appearing in the search results immediately may not prove that it was never sent, due to indexing delays or search-filter mismatches. I’d keep that case in review unless the workflow has enough evidence to safely retry.
The Postgres unique constraint on (invoice_id, stage) is also a good improvement for concurrent scheduled runs. I’d treat it as a durable claim on the reminder attempt, while keeping the final delivery outcome separate from the claim itself.
That distinction helps prevent duplicate attempts without incorrectly treating a database record as proof of email delivery.
1 Like
Fair point, “not found” is weaker evidence than “found”. I’d tighten the not-found branch so it never retries on a single search:
- Found in Sent: mark it sent and clear
pending_stage.
- Not found, and
pending_at is under 24 hours old: leave it pending and check again on the next run, since that covers indexing lag.
- Still not found after 24 hours and at least two searches: send it to a person to review. No automatic resend.
Searching on a tag that only lives in the subject, like INV-1042 R2, also cuts down on filter mismatches compared with matching on the recipient or the body.
Agreed on keeping the claim and the outcome separate. In Postgres I’d model it like this:
create table reminder_attempts (
invoice_id text not null,
stage int not null,
claimed_at timestamptz not null default now(),
status text not null default 'claimed', -- claimed | sent | review | failed
gmail_id text,
primary key (invoice_id, stage)
);
-- claim: insert ... on conflict do nothing returning invoice_id; no row back = skip
-- after Gmail: update status = 'sent', gmail_id = $1
The insert only stops two runs from both trying the same reminder. A row moves to sent only once Gmail returns a message id, and anything still claimed after the grace period lands in the same review queue.
1 Like
That’s a sensible refinement. Keeping the attempt in a pending state during the reconciliation window avoids treating a delayed search result as proof that the email was never sent.
I also like that the unique constraint protects the claim, while the status and Gmail message ID represent the recorded outcome separately. The remaining ambiguous cases are exactly where a review queue is safer than an automatic retry.
This is a useful pattern for other external side effects where the database and the destination system cannot share an atomic transaction.
1 Like
Agreed. One addition for other side effects: when the destination accepts an idempotency key, most of that ambiguity goes away. Stripe, for example, takes an Idempotency-Key header, so retrying a timed-out request with the same key returns the original result instead of charging twice.
I build the key from the row and the stage, like inv-1042-stage2, and write it to the claim row before the call. A timeout can then be retried safely, and the review queue is only needed for destinations like Gmail that have no equivalent.
1 Like
Good point. Idempotency keys help when the destination supports them, but the timeout case still needs careful handling.
The client may time out even after the destination has completed the operation. Reusing the same key can make retries safe only within the destination’s documented idempotency behavior and retention window.
For destinations without that support, reconciliation and a manual review path are safer than assuming a timeout means the operation failed.
1 Like
One more case I would test is two executions overlapping. Both could read the same last_stage_sent value before either writes it back, then both send the reminder. That is a different failure from Gmail succeeding while the sheet update fails.
Could you run two test executions against the same invoice and stage, with both paused after the initial read? A stable invoice ID plus stage would identify the same intended reminder in both runs. If overlap is possible, the claim on that work needs to be atomic; another ordinary sheet column alone would still leave a read/write race. How are overlapping runs handled in your setup?
Good catch, and you’re right that it’s a different failure from Gmail succeeding while the sheet update fails. I haven’t run that paused-overlap test yet, so I can’t say what the sheet version does under a real race. I’d expect it can double-send, because a Sheets read followed by a later write is never atomic.
How I keep overlap unlikely today: the reminder workflow is the only writer to that tab, it runs from a single Schedule Trigger with an interval much longer than one run takes, and it has no webhook or manual entry point. That makes overlap unlikely, not impossible.
If overlap is possible (a webhook entry point, a second instance, or queue mode with several workers), the claim has to be atomic. With Postgres it’s one statement, with a unique index on (invoice_id, stage):
INSERT INTO reminder_claims (invoice_id, stage, claimed_at)
VALUES ($1, $2, now())
ON CONFLICT (invoice_id, stage) DO NOTHING
RETURNING invoice_id;
Only the run that gets a row back sends. The other gets zero rows and an IF node stops it. The sheet then just shows what was sent; it isn’t the lock anymore.
Agreed, and the retention window is the part people miss. Stripe, for example, can prune keys once they’re at least 24 hours old, so a retry after that is treated as a new request. I only auto-retry inside a short window and send anything older to the same reconciliation and review path you describe.
One distinction worth making: Stripe’s idempotency-key retention is a retry-window concern, while the overlap case is a concurrency concern. For overlapping reminder runs, the claim must be atomic so only one execution can send for a given invoice-stage pair. A database uniqueness constraint with INSERT ... ON CONFLICT DO NOTHING is one way to enforce that. Retries outside the provider’s retention window need a separate reconciliation strategy.
Great thread, and Shital’s “keep the claim and the outcome separate” is the line I’d frame.
One source of double sends nobody has mentioned yet: n8n’s own Retry On Fail on the Gmail node. It re-runs the whole node when its first item fails, not just the failed item, so if one run sends five reminders and the first hits a temporary error, the retry emails the other four clients a second time. I found that out testing my own quote → invoice → receipt template, and now every node that can reach a client has Retry On Fail off. A failed send becomes a note on the row, and a person decides.
Two smaller things from the same build:
- The “Sending…” mark goes on every row in the run in one sheet write, before anything is made or sent. If that write fails, the run stops and nothing goes out; a mark that’s still there on the next run means “check Sent first”.
- The PDF step’s key includes a revision (
1001-deposit-r1), so a re-run within 24 hours gets the same document back and isn’t charged again, and a changed amount under the same key is refused until someone raises the revision. Gmail has no key, so the email itself still needs the Sent-folder check you described.
Andrew’s overlap point stands for my version too: a sheet can’t make the claim atomic. Your INSERT … ON CONFLICT DO NOTHING is the real fix there.