Things to watch out for with WebRTC

Originally posted on 2024-01-19

Here are a few of the things that have bitten me (several times) since I started working with WebRTC.

Set up your handlers immediately!

Some people like to say “there’s no time like the present”. It’s annoying but in this case it’s necessary. If you are creating a data channel with WebRTC most libraries will offer you some kind of callback to indicate a new data channel was created.

When that callback is called you must set up your handlers immediately or you risk losing messages.

The setup process usually goes something like this:

  • OnDataChannel is called to notify you that there’s a new data channel coming
  • You set up the OnOpen handler (optional)
  • You set up the OnMessage handler

What you may not realize is that once OnDataChannel returns the library is ready to start handling messages. If you set up the OnOpen handler and/or the OnMessage handler after that and a message comes in it will get dropped even if you are using a channel with ordered delivery, retries, etc.

This is because the message was delivered but nobody was waiting for it.

Use OnOpen to let you know when it’s safe to start sending data

It’s tempting to see that there’s a new data channel ready for you and immediately send a message on it. However, if you do this you’ll likely get an error because the channel isn’t ready. The library may or may not take care of this for you by buffering your message but it’s better to just put the send logic in the OnOpen handler itself than hope the library does what you want.