𝗬𝗼𝘂𝗿 𝗧𝗲𝗹𝗲𝗴𝗿𝗮𝗺 𝗕𝗼𝘁 𝗥𝗲𝗽𝗹𝗶𝗲𝘀 𝗧𝘄𝗶𝗰𝗲? 𝗜𝘁'𝘀 𝗧𝗶𝗺𝗶𝗻𝗴, 𝗡𝗼𝘁 𝗔 𝗟𝗼𝗴𝗶𝗰 𝗕𝘂𝗴
Your Telegram bot replies to the same message twice. An n8n flow processes an order, then repeats it ten seconds later. You check your code and find no errors. You think your logic is broken.
It is not. These bugs happen because of timing.
Here are the three reasons this happens and how you fix them.
- The Timeout Retry
Telegram waits for an HTTP 200 response. If your code does heavy work before answering, you might hit a timeout. A slow database or a slow API causes this. Telegram thinks the delivery failed and sends the same update again.
The fix: Acknowledge first, process second.
- Receive the update.
- Put the update in a queue.
- Return a 200 status immediately.
- Process the work in a background task.
- The Duplicate Event
Network issues or restarts cause retries. You must assume every event arrives more than once. Use idempotency to make duplicate events harmless.
Every update has a unique ID. Use it to track what you already processed.
- Check if the update_id exists in your database or Redis.
- If it exists, stop.
- If it is new, save the ID and process the message.
This ensures you process an order once even if the event arrives three times.
- The Race Condition
A user taps a button twice. Two updates arrive at the same time. Both processes read the same balance, subtract a value, and save it. You end up with the wrong total.
Your logic is fine, but the runs overlap.
The fix: Use a lock.
- Lock the user ID before you start the work.
- Update the balance.
- Release the lock.
This forces the second update to wait until the first one finishes. In n8n, use a queue or a step to wait for the previous execution.
These bugs are hard to find. Your code works fine during manual tests. They only appear under real traffic when things get busy.
Stop looking for logic errors. Start logging your update IDs and your timing. When you see the same ID twice in your logs, you found your problem.
Source: https://dev.to/lamas51/your-telegram-bot-replies-twice-its-timing-not-a-logic-bug-2f4j