I'm building an SMS-enabled app that allows the user to communicate with an external contact. As incoming messages arrive, I save them to my database so that they can be displayed in the app.
In testing, everything is working great for one-off messages, but I'm having trouble with messages longer than 160 characters, which are actually broken up into multiple messages.
When an incoming message comes in via SMS, I'm checking whether we already got a message from that number within the past few seconds. If we have, I append to the existing record in my DB, rather than saving a new record.
// First message arrives:
record == "This is the first message."
// Second message arrives:
record == "This is the first message. This is the second message."
My problem is that sometimes the two messages arrive so quickly that the first record hasn't finished saving yet. When the second process queries for an existing record, it doesn't find one and creates a new one.
// First message arrives:
record1 == "This is the first message."
// Second message arrives, first isn't saved yet:
record1 == "This is the first message."
record2 == "This is the second message."
This makes a particularly bad user experience when there's a message with three or more segments, when the following happens:
// First message arrives:
record1 == "This is the first message."
// Second message arrives, first isn't saved yet.
record1 == "This is the first message."
record2 == "This is the second message."
// Third message arrives, first has now been saved.
record1 == "This is the first message. This is the third message."
record2 == "This is the second message."
Without abandoning my plan to re-combine these messages, how can I get the messages to appear in the right order?
*Note: * Ideally, I'd like to know when saving a message whether it is a first (new) message or a follow-up message. Receiving a new message triggers an email notification to the user, but I don't want to send multiple notifications if they're receiving one long message.