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.
Comments
Here are some guesses.
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.
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/ 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.
byte[] data = Serialize(msgs) - is greater then Array can handle (Or maybe use data.LongLength and write a few times to the stream)
Message too long so you get a server Time Out (and this might grow the next time you try)....
Lamar,
Continue this to the obvious conclusion, you are almost there, although you went way ahead.
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
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?
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.
Large object Heap ...?
Thread.Sleep(5000)
If it takes more than 5 seconds to send the message you'll start sending them twice
Nice unbounded ResultSet, the story about it in Release It!'s antipattern chapter shows what happens with them...
@Aguiar
Doesn't it start sleeping only after srv.ProcessMessages(); is done.
While(true) is a bit concerning :-)
@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.
@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.
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.
Sorry, make that "HTTP put", not "HTTP get".
@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
(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.