Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
Possible race condition with EventSource?

I am using Server Sent Events (SSE) and my code to connect to my SSE backend looks like this:

function sseSubscribe() {
  events = new EventSource("/v1/sse/" + sseID + "/" + lastEventId);

  events.addEventListener("message", sseHeartbeat);
  events.addEventListener("error", sseError);
  events.addEventListener("reply", sseReply);
  events.addEventListener("refresh", sseRefresh);
}

This function is called to setup the initial SSE connection, but also when a reconnection is desired (because the connection broke for whatever reason).

On the server, if the lastEventId is greater than 0, it will stream any missing messages to the client.

So, hypothetically, if doing new EventSource() blocked, this wouldn't work, because the events would be streamed back to the browser before the corresponding event handlers (reply, refresh, etc.) were registered.

However, to my knowledge, this is not the case (I believe calling new EventSource is a non-blocking operation? Not sure though). However, I suppose it's possible if the user's computer was slow enough, and their connection was fast enough, that maybe missing messages could be streamed back before the listeners were registered.

Is this a reasonable fear, or should I feel relatively safe with the above code?

To reiterate, this code seems to work, but my fear is that messages may be streamed back from the new EventSource connection before the corresponding handlers are added. Is this reasonable, or does it have a 0% chance of happening?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The connection occurs after the current Javascript execution has completed. I believe this would be safe to assume for all browsers, though I don't have a definitive reference.

For example, Chrome starts the connection from a timer, which probably ties into the same event loop as, for example, setTimeout: https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/eventsource/event_source.cc;l=99?q=EventSource&ss=chromium

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!