Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda