How does Twitch count views?

Just curious about how Twitch servers and back-end get information on how many viewers a livestream has at any time?

I understand that when a user enters the stream its easy to configure it so that the back-end gets a ping from the client and the view count can be updated.

But when the user leaves, how does the back end get the info?

I mean, the user can just simply close the window without actually navigating further to other pages on the site. Then, the back-end can’t get the information needed, right?

So how do twitch actually tell how many viewers a stream currently have?

Thanks!

PS:
Sorry for my English and “developer language”. I’m neither a native English speaker or a developer… :slight_smile:

You need to be actively download the video to be counted as a viewer.

Theres multiple ways to do it and I’m not sure which twitch uses exactly but if you’re looking to do something similar and fishing for a solution, then there are onbeforeunload events that browsers fire when you close them. Whether its closing the tab, or the whole browser, they fire an event signaling it which allows developers to handle these exits however they please. In addition, a session can be created and managed by the server, the life of the session could be very short and is kept alive by the constant streaming of data/http requests. When the user exits, the scripts that kept the session alive don’t run since nothing is being streamed and the server then kills the session. When the session dies it removes it from the viewer count. Twitch could also use its own propriety method but its most likely one of these or a combination of both.