Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 6,007 | Comments: 44,761

filter by tags archive

ChallengeWhat is wrong with this code

time to read 2 min | 282 words

Let us assume that we have the following piece of code. It has a big problem in it. The kind of problem that you get called at 2 AM to solve.

Can you find it? (more below)

public static void Main()

public void ProcessMessages()
	   var msgs = GetMessages();
	   byte[] data = Serialize(msgs);
	   var req =  WebRequest.Create("http://some.remote.server");
	   req.Method = "PUT";
	   using(var stream = req.GetRequestStream())
	   var resp = req.GetResponse();
	   resp.Close();// we only care that no exception was thrown
	   MarkMessagesAsHandled(msgs); // assume this can't throw 
		// bummer, but never mind,
		// we will get it the next time that ProcessMessages 
		// is called

public Message[] GetMessages()
    List<Message> msgs = new List<Message>();
    using(var reader = ExecuteReader("SELECT * FROM Messages WHERE Handled = 0;"))
        msgs.Add( HydrateMessage(reader) );
    return msgs.ToArray();

This code is conceptual, just to make the point. It is not real code. Things that you don't have to worry about:

  • Multi threading
  • Transactions
  • Failed database

The problem is both a bit subtle and horrifying. And just to make things interesting, for most scenarios, it will work just fine.

More posts in "Challenge" series:

  1. (28 Apr 2015) What is the meaning of this change?
  2. (26 Sep 2013) Spot the bug
  3. (27 May 2013) The problem of locking down tasks…
  4. (17 Oct 2011) Minimum number of round trips
  5. (23 Aug 2011) Recent Comments with Future Posts
  6. (02 Aug 2011) Modifying execution approaches
  7. (29 Apr 2011) Stop the leaks
  8. (23 Dec 2010) This code should never hit production
  9. (17 Dec 2010) Your own ThreadLocal
  10. (03 Dec 2010) Querying relative information with RavenDB
  11. (29 Jun 2010) Find the bug
  12. (23 Jun 2010) Dynamically dynamic
  13. (28 Apr 2010) What killed the application?
  14. (19 Mar 2010) What does this code do?
  15. (04 Mar 2010) Robust enumeration over external code
  16. (16 Feb 2010) Premature optimization, and all of that…
  17. (12 Feb 2010) Efficient querying
  18. (10 Feb 2010) Find the resource leak
  19. (21 Oct 2009) Can you spot the bug?
  20. (18 Oct 2009) Why is this wrong?
  21. (17 Oct 2009) Write the check in comment
  22. (15 Sep 2009) NH Prof Exporting Reports
  23. (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
  24. (01 Sep 2009) Why isn’t select broken?
  25. (06 Aug 2009) Find the bug fixes
  26. (26 May 2009) Find the bug
  27. (14 May 2009) multi threaded test failure
  28. (11 May 2009) The regex that doesn’t match
  29. (24 Mar 2009) probability based selection
  30. (13 Mar 2009) C# Rewriting
  31. (18 Feb 2009) write a self extracting program
  32. (04 Sep 2008) Don't stop with the first DSL abstraction
  33. (02 Aug 2008) What is the problem?
  34. (28 Jul 2008) What does this code do?
  35. (26 Jul 2008) Find the bug fix
  36. (05 Jul 2008) Find the deadlock
  37. (03 Jul 2008) Find the bug
  38. (02 Jul 2008) What is wrong with this code
  39. (05 Jun 2008) why did the tests fail?
  40. (27 May 2008) Striving for better syntax
  41. (13 Apr 2008) calling generics without the generic type
  42. (12 Apr 2008) The directory tree
  43. (24 Mar 2008) Find the version
  44. (21 Jan 2008) Strongly typing weakly typed code
  45. (28 Jun 2007) Windsor Null Object Dependency Facility



Here are some guesses.

  1. If any exception is thrown after you send the data to the server but before you call MarkMessagesAsHandled(..) then the same Messages will be be sent again.

  2. You don't close "resp" in a finally block (if an exception is thrown - using up system resources).

(3. If no messages are returned from GetMessages() or it throws an exception.)

  1. If there is to much messages to handle.
Ayende Rahien

1/ Assume that MarkMessagesAsHandled can't throw, if the other server sent an OK reply, we will get the data and mark them. If it didn't, this is failure case and we should retry.

2/ doesn't really matter. In general, you are correct, but if an exception is thrown from GetResponse() the response object will be disposed by the system.

3/ no messages means that the other side gets an empty message, and just ignore it. No issue. Assume that GetMessages can't throw.

4/ you are close


If there are too many messages in the system, the request stream will exceed the max bytes allowed by the http server you are posting to, and the post request will fail.

  1. byte[] data = Serialize(msgs) - is greater then Array can handle (Or maybe use data.LongLength and write a few times to the stream)

  2. Message too long so you get a server Time Out (and this might grow the next time you try)....

Ayende Rahien


Continue this to the obvious conclusion, you are almost there, although you went way ahead.

Ayende Rahien

1/ is unlikely to happen. And anyway, 4GB + of msgs isn't quite the thing to have.

2/ And that is the main issue, yep. What is worth, once you got to that point, you are doomed, because the amount of work will just get bigger and bigger, and you''ll always fail

Tobin Harris

So does that mean you need to use "SELECT TOP 100 *" to limit the number of messages sent in any one pass?

Or would you just split the payload up (the array) and send it using multiple requests?

Ayende Rahien

Yes, you deal with them in a piece by piece.

And you want to do this as early as possible, so TOP / LIMIT is the way to go


You need to ensure your messages buffer is still empty before sleeping:

while (srv.ProcessMessages()) ;

If the rate of incoming messages is "too high" (whereby it would take 5 seconds or greater to send a batch them via HTTP PUT) then the buffer gets "overfilled" during the sleep and you wind up waiting for no reason. Then, by the time you've woken up, you now have 10 "seconds of data" in the buffer, and you wind up getting backlogged very quickly.

Andres Aguiar


If it takes more than 5 seconds to send the message you'll start sending them twice

Markus Zywitza

Nice unbounded ResultSet, the story about it in Release It!'s antipattern chapter shows what happens with them...



Doesn't it start sleeping only after srv.ProcessMessages(); is done.

Dave THe Ninja

While(true) is a bit concerning :-)

Max Schmeling

@Yitzchok - I actually thought the same as Aguiar at first, but you're right: ProcessMessages is synchronous so Thread.Sleep is called after it finishes.

Peter Ritchie

@Anon why? ProcessMessages can take as long as it wants. There's just a 5 second delay between when ProcessMessages finishes and when it is called next.

Peter Ritchie

I believe there is a default timeout and a default size limit to HTTP get with .NET. If a timeout occurs because there is too much data you'll end up simply reprocessing all the messages in vain and be doomed to more timeouts as the size increases from iteration to iteration.

Peter Ritchie

Sorry, make that "HTTP put", not "HTTP get".



Consider a case where you can send 1000 messages per second.

Time 0.0s: We call Sleep(5000)

Time 0.1s-5.0s: We start receiving messages at the rate of 1200 messages per second.

Time 5.0s: We wake up and pop the 6000 messages and start sending them.

Time 11.0s: We're done sending them, and will now go to sleep, even though there's already 7200 more messages to send.

Time 16.0s: We wake back up, and now have to process 13200 messages. This takes 13.2 seconds.

Time 29.2s: We're done sending. There are now 15840 new messages to process, but we go to sleep again for 5 more seconds.

Time 34.2s: We wake back up, and now have 21840 messages to process.

.. etc.

We call ProcessMessages once


(Oops, submitted to early)

Basically our backlog after 34 seconds is 21840 messages when in reality it should be closer to (1200 - 1000) * 34 = 6800. The backlog increases very quickly.


var msgs = GetMessages();

Ahh, good 'ol ReSharper :)


The byte[] could grow larger than what the "PUT" request is able to handle. Something akin to Apache's LimitRequestSize restriction.


Can you do List ? I think that is the problem with the code.


So does a req.GetResponse() threw a WebException when the message is too long? if it does then it's not so hard to debug but yes the bug is very subtle.


There is never a check for zero messages returned from GetMessages(). There will be no need to send an empty array every 5 seconds...


Infinite loop !!

even if one message causes an exception (which is ignored) the queue keeps getting bigger and bigger since the bad entry will never get marked as handled.

Eg. say there are 10 entries and

the data in the 1st one causes an exception (hey there can be bugs - its not a perfect world)

Every time we run the select * from .. , this entry is back in queue.

causing every single entry after it to get stuck as this one fellow cannot be processed.

the queue now starts building and the entry never gets marked as done.

This can cause other things like outofmemory..etc if the queue starts building.

So get up at 2 in the morning

run : update Messages set Handled = where entry_id = < id of culprit>

the queue is back functioning.

Next day:

Fix : in the catch block: update the entries as sidelined (with retries if needed )


If ProcessMessages() takes longer than five seconds then you have a problem. I encountered something similar to this in a a little (.Net0 service app I was asked to look at a while back. It was supposed to hit the database every once in a while in order to figure out whether or not any new safety incidents had occurred and it would email a report off to a department head if anything qualified. The problem was that the original developer interpreted "every once in a while" to mean five seconds. The combination of a poorly designed database and inefficient processing within the application virtually guaranteed that the five second timer would fire before the previous processing was completed. Sucked.

Comment preview

Comments have been closed on this topic.


No future posts left, oh my!


  1. Speaking (3):
    23 Sep 2015 - Build Stuff 2015 (Lithuania & Ukraine), Nov 18 - 24
  2. Production postmortem (11):
    22 Sep 2015 - The case of the Unicode Poo
  3. Technical observations from my wife (2):
    15 Sep 2015 - Disk speeds
  4. Find the bug (5):
    11 Sep 2015 - The concurrent memory buster
  5. Buffer allocation strategies (3):
    09 Sep 2015 - Bad usage patterns
View all series



Main feed Feed Stats
Comments feed   Comments Feed Stats