Challenge: What is wrong with this code

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()
{
	while(true)
	{
		srv.ProcessMessages();
		Thread.Sleep(5000);
	}
}

public void ProcessMessages()
{
	try
	{
	   var msgs = GetMessages();
	   byte[] data = Serialize(msgs);
	   var req =  WebRequest.Create("http://some.remote.server");
	   req.Method = "PUT";
	   using(var stream = req.GetRequestStream())
	   {
		   stream.Write(data,0,data.Length);
	   }
	   var resp = req.GetResponse();
	   resp.Close();// we only care that no exception was thrown
	   
	   MarkMessagesAsHandled(msgs); // assume this can't throw 
	}
	catch(Exception)
	{
		// 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;"))
    while(reader.Read())
    {
        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.

Print | posted on Wednesday, July 02, 2008 6:31 AM

Feedback


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 7:25 AM Yitzchok

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.)

4. If there is to much messages to handle.


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 7:38 AM 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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 8:07 AM Lamar

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.


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 8:17 AM Yitzchok

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)....


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 8:27 AM Ayende Rahien

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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 8:29 AM 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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 12:50 PM 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?


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 12:57 PM 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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 3:16 PM Anon

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.


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 3:58 PM Charles Wain

Large object Heap ...?


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 4:05 PM Andres Aguiar

Thread.Sleep(5000)

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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 4:45 PM Markus Zywitza

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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 6:00 PM Yitzchok

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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 6:02 PM Dave THe Ninja

While(true) is a bit concerning :-)


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 6:38 PM 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.


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 7:04 PM 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.


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 7:06 PM 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.


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 7:07 PM Peter Ritchie

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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 9:13 PM Anon

@Peter:

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


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 9:17 PM Anon

(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.


Gravatar

# re: Challenge: What is wrong with this code 7/2/2008 11:07 PM hmemcpy

var msgs = GetMessages();

Ahh, good 'ol ReSharper :)


Gravatar

# re: Challenge: What is wrong with this code 7/3/2008 8:32 AM dp

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


Gravatar

# re: Challenge: What is wrong with this code 7/3/2008 8:52 AM Zach

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


Gravatar

# re: Challenge: What is wrong with this code 7/3/2008 10:22 AM firefly

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.


Gravatar

# re: Challenge: What is wrong with this code 7/3/2008 10:34 AM leppie

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


Gravatar

# re: Challenge: What is wrong with this code 7/3/2008 10:54 AM Ajay

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 = <sideline> 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 )


Gravatar

# re: Challenge: What is wrong with this code 7/4/2008 2:33 AM Garren

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.

Comments have been closed on this topic.