ChallengeWhat 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.
More posts in "Challenge" series:
- (03 Feb 2025) Giving file system developer ulcer
- (20 Jan 2025) What does this code do?
- (01 Jul 2024) Efficient snapshotable state
- (13 Oct 2023) Fastest node selection metastable error state–answer
- (12 Oct 2023) Fastest node selection metastable error state
- (19 Sep 2023) Spot the bug
- (04 Jan 2023) what does this code print?
- (14 Dec 2022) What does this code print?
- (01 Jul 2022) Find the stack smash bug… – answer
- (30 Jun 2022) Find the stack smash bug…
- (03 Jun 2022) Spot the data corruption
- (06 May 2022) Spot the optimization–solution
- (05 May 2022) Spot the optimization
- (06 Apr 2022) Why is this code broken?
- (16 Dec 2021) Find the slow down–answer
- (15 Dec 2021) Find the slow down
- (03 Nov 2021) The code review bug that gives me nightmares–The fix
- (02 Nov 2021) The code review bug that gives me nightmares–the issue
- (01 Nov 2021) The code review bug that gives me nightmares
- (16 Jun 2021) Detecting livelihood in a distributed cluster
- (21 Apr 2020) Generate matching shard id–answer
- (20 Apr 2020) Generate matching shard id
- (02 Jan 2020) Spot the bug in the stream
- (28 Sep 2018) The loop that leaks–Answer
- (27 Sep 2018) The loop that leaks
- (03 Apr 2018) The invisible concurrency bug–Answer
- (02 Apr 2018) The invisible concurrency bug
- (31 Jan 2018) Find the bug in the fix–answer
- (30 Jan 2018) Find the bug in the fix
- (19 Jan 2017) What does this code do?
- (26 Jul 2016) The race condition in the TCP stack, answer
- (25 Jul 2016) The race condition in the TCP stack
- (28 Apr 2015) What is the meaning of this change?
- (26 Sep 2013) Spot the bug
- (27 May 2013) The problem of locking down tasks…
- (17 Oct 2011) Minimum number of round trips
- (23 Aug 2011) Recent Comments with Future Posts
- (02 Aug 2011) Modifying execution approaches
- (29 Apr 2011) Stop the leaks
- (23 Dec 2010) This code should never hit production
- (17 Dec 2010) Your own ThreadLocal
- (03 Dec 2010) Querying relative information with RavenDB
- (29 Jun 2010) Find the bug
- (23 Jun 2010) Dynamically dynamic
- (28 Apr 2010) What killed the application?
- (19 Mar 2010) What does this code do?
- (04 Mar 2010) Robust enumeration over external code
- (16 Feb 2010) Premature optimization, and all of that…
- (12 Feb 2010) Efficient querying
- (10 Feb 2010) Find the resource leak
- (21 Oct 2009) Can you spot the bug?
- (18 Oct 2009) Why is this wrong?
- (17 Oct 2009) Write the check in comment
- (15 Sep 2009) NH Prof Exporting Reports
- (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
- (01 Sep 2009) Why isn’t select broken?
- (06 Aug 2009) Find the bug fixes
- (26 May 2009) Find the bug
- (14 May 2009) multi threaded test failure
- (11 May 2009) The regex that doesn’t match
- (24 Mar 2009) probability based selection
- (13 Mar 2009) C# Rewriting
- (18 Feb 2009) write a self extracting program
- (04 Sep 2008) Don't stop with the first DSL abstraction
- (02 Aug 2008) What is the problem?
- (28 Jul 2008) What does this code do?
- (26 Jul 2008) Find the bug fix
- (05 Jul 2008) Find the deadlock
- (03 Jul 2008) Find the bug
- (02 Jul 2008) What is wrong with this code
- (05 Jun 2008) why did the tests fail?
- (27 May 2008) Striving for better syntax
- (13 Apr 2008) calling generics without the generic type
- (12 Apr 2008) The directory tree
- (24 Mar 2008) Find the version
- (21 Jan 2008) Strongly typing weakly typed code
- (28 Jun 2007) Windsor Null Object Dependency Facility
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<Message> ? 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 = <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 )
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