A 98% Drop and No Errors: The Email Flow That Quietly Died
Reading time: ~ 7 minutes
Some bugs announce themselves. A page 500s, an alert fires, a customer emails support, and you're off to the races. The dangerous ones are quieter. They don't crash anything. They just slowly stop doing what they're supposed to do, and because nothing is technically broken, nobody finds out until the damage is already weeks deep.
That's the story of a follow-up email flow that quietly stopped sending. It had been running fine for one of our clients for years. Then, over about six weeks, it went almost completely silent, and not a single error was raised the entire time.
What the flow was supposed to do
As part of a key, long-running marketing promotion, the client ships printed materials to anyone who requests them. It's a channel that's been an important part of their inbound funnel for years. A few days after a sample is delivered, a friendly "checking in, what did you think?" email goes out. It's a small touch, but it's a real one: it nudges people who took a sample but haven't come back to actually place an order.
Mechanically, it's a chain. A scheduled worker runs once a day, figures out who's due for a follow-up, and emits an event into Klaviyo (our client's email platform). That event triggers a Klaviyo flow, which, after a built-in delay, sends the actual email. The important part for this story: the daily worker is the engine. If it stops emitting events, the whole flow downstream goes quiet, and Klaviyo has nothing to react to.
The collapse
Klaviyo was the first to notice. It flagged an unexpected drop in the volume of the metric that powers the follow-up flow. When we pulled the numbers, the shape was unmistakable:
- May: 3,284 follow-up events
- June: 76
A ~98% drop, effectively overnight. What made it confusing was that everything upstream was healthy and growing: sample confirmations, verifications, and shipping notifications were all firing normally, with volume trending up. Only the last step in the chain, the follow-up, had fallen off a cliff.
That combination, a healthy funnel with a dead final step and no errors anywhere, is the tell. It meant the follow-up worker was failing silently: no crash, no alert, just a job that had quietly stopped keeping up.
The hunt
We profiled the daily worker with Scout and the picture came together fast: roughly 7.5 minutes per run, 98% of it in ActiveRecord, with a classic N+1 flagged on the user lookup and order count. The job wasn't computing anything expensive. It was drowning in database queries.
Here's the code at the heart of it. For every candidate sample request, it did one user lookup and one order count:
def pending_follow_up pending = [] candidate_requests.each do |request| # Match samples against users by lowercase email. user = User.where('LOWER(email) = ?', request.email.downcase).first if user.nil? || user.guest_only? pending << request next end # Skip anyone who already placed an order since requesting the sample. count = user.orders.closed .where('placed_at > ?', request.shipping_notification_sent_at) .count pending << request if count.zero? end pending end
When the candidate set was small, this was fine. But as the client's sample volume grew, the candidate set climbed past ~5,000, and now the job was firing more than ten thousand queries every run.
Then came the part that explained the silence. The single daily run had gotten so slow that it could no longer finish before a routine deploy restarted the process. Each run was getting cut off partway through, making about one follow-up's worth of progress before it was killed, then starting over the next day, only to fall further behind. The backlog grew a little more each day.
And crucially: being interrupted is not the same as erroring. The process didn't raise an exception. It was simply terminated mid-run. So Sentry had nothing to catch, and our AWS alarms had nothing to trip. From every monitoring tool's point of view, the job was running every day exactly as scheduled. It just wasn't finishing.
The fix
The root cause was the N+1, so the fix was to stop asking the database one question per candidate and start asking it one question for all candidates. The rewritten qualification is set-based: it resolves every matching user in one query and every user's most recent closed-order date in one more:
def pending_follow_up candidates = candidate_requests return [] if candidates.empty? users_by_email = matching_users_by_email(candidates) latest_closed_order = latest_closed_order_at_by_user(users_by_email.values) candidates.select do |request| user = users_by_email[request.email.downcase] next true if user.nil? || user.guest_only? ordered_at = latest_closed_order[user.id] ordered_at.nil? || ordered_at <= request.shipping_notification_sent_at end end # One query: the first user per candidate email, matched case-insensitively. def matching_users_by_email(candidates) emails = candidates.map { |r| r.email.downcase }.uniq {}.tap do |by_email| User.where('LOWER(email) IN (?)', emails).order(:id).each do |user| by_email[user.email.downcase] ||= user end end end # One query: the most recent closed-order date per user. def latest_closed_order_at_by_user(users) ids = users.reject(&:guest_only?).map(&:id) return {} if ids.empty? Order.closed.where(user_id: ids).group(:user_id).maximum(:placed_at) end
Everyone who qualified for a follow-up still qualifies, under the same rules as before. The win is purely in performance: the work now stays flat no matter how large the backlog grows.
But if we'd stopped at the N+1, we'd have fixed the bug and left the silence intact. The more valuable lesson from this incident wasn't "we had a slow query." It was "a job failed for six weeks, and nothing told us." So the rest of the fix was about making that failure mode impossible, or at least loud:
- Async fan-out. Instead of sending each email inline inside the daily run, the scheduler now enqueues one job per candidate. A single slow or hung send can no longer stall the entire run.
- An idempotent sender. The "have we already sent this?" guard (
with_lock+ afollow_up_sent_atcheck) moved into the per-recipient worker, so a job can be safely retried or re-enqueued without ever sending someone a duplicate. - A fail-fast timeout. We added a 10-second read / 5-second open timeout on the Klaviyo call, so one hung request fails quickly and retries instead of hanging long enough to eat the run.
Individually, these are small. Together they turn a job that could quietly stall into one that keeps moving and, if something does go wrong, fails in a way that surfaces instead of hides.
Proving it stays fixed
An N+1 is easy to reintroduce by accident. Someone adds an innocent-looking .each a year from now, and you're right back here. So the fix shipped with a regression test that asserts the query count does not grow with the number of candidates:
should "issue a constant number of queries regardless of candidate volume" do build_qualifying_candidates(3) baseline = count_queries { worker.send(:pending_follow_up) } build_qualifying_candidates(30) # 33 total scaled = count_queries { worker.send(:pending_follow_up) } assert_operator scaled, :<=, baseline + 2, "query count grew with candidate volume (N+1 regression)" end
We confirmed it fails on the old implementation (10 queries for 3 candidates, 70 for 33) and passes on the new one, where the count stays flat at roughly six regardless of volume. The bug can't come back without turning the build red.
The judgment call nobody writes tests for
Here's the part that had nothing to do with code, and mattered just as much.
The moment we deployed the fix, the worker could finish a full run again, which meant it would immediately try to email the entire backlog it had been unable to work through. At the time of the fix, that was roughly 4,650 people owed a follow-up, some of them from shipments five to forty days old.
Sending them all at once was clearly wrong. Imagine getting a "so, how did you like your sample?" email five weeks after the fact. It comes across as broken rather than thoughtful. But sending none of them meant missing thousands of legitimate touchpoints the system genuinely owed people.
We chose the middle: send the recent shipments, suppress the stale tail. A shipment from the last week or so still makes for a timely, natural check-in. Anything much older gets quietly marked as handled so it doesn't fire. We built that as a one-off, dry-run-able rake task so we could see the split before committing to it:
# Mark the stale tail as already handled so only recent shipments # get a follow-up on the next run. DAYS controls the cutoff (default 10); # DRY_RUN=1 reports the counts without changing anything. task :suppress_stale_follow_ups => :environment do days = Integer(ENV.fetch("DAYS", 10)) cutoff = days.days.ago stale = SampleRequest.awaiting_follow_up.where("shipping_notification_sent_at < ?", cutoff) recent = SampleRequest.awaiting_follow_up.where("shipping_notification_sent_at >= ?", cutoff) puts "recent (will be emailed): #{recent.count}" puts "stale (to suppress): #{stale.count}" next if ENV["DRY_RUN"] == "1" stale.update_all(follow_up_sent_at: Time.current) end
We ran it dry first, shared the numbers with the client, and let them make the final call on where to draw the line before anything went out. The technical fix restored the machine. This decision was about being a good steward of the client's relationship with their customers, and that's not something a test suite can validate for you.
Where it landed
The fix went to production on July 1. Then we did the thing that's easy to skip once the pressure's off: we actually watched it recover, over weeks, to make sure it held.
- June: 76 (the collapse), then July: 3,131, then August: 4,379: fully recovered and running above the pre-incident baseline, with no slide back toward zero at any point in the eight weeks after deploy.
- The daily pattern is exactly what the worker should produce: volume concentrated on Mondays, tapering through the week, zero on weekends when the cron doesn't run.
- Downstream, the emails that the restored events matured into landed for real: for one representative week, 741 of 746 delivered (99.3%), with a 49% open rate.
That last number matters most. It's the confirmation that this was never just an events-in-a-dashboard problem. Real "checking in" emails were reaching real inboxes again.
The takeaway
If there's one thing worth carrying out of this, it's that a job that's "just slow" can actually be a job that's failing, and the absence of errors is not the same as the presence of success. The N+1 was the bug, but the six weeks of silence was the real problem, and fixing the query without fixing the visibility would have left us one growth spurt away from the exact same incident.
So we fixed all three: the query that caused it, the design that let it fail invisibly, and the regression test that keeps it from coming back. And we made a human call about the backlog that no amount of engineering could make for us.
The quiet failures are the ones to watch for. The loud ones take care of themselves.
The hard part of a bug like this is noticing it at all. Catching the quiet ones, like a background job slowly falling behind or a metric drifting toward zero, is a lot of what our Rails Maintenance Retainer is for: an experienced team watching the corners of your application so problems surface in week one instead of week six. If your Rails app has been running long enough that you're not entirely sure what it might be quietly not doing, we'd be glad to take a look.