<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anastasiia Pristupa on Medium]]></title>
        <description><![CDATA[Stories by Anastasiia Pristupa on Medium]]></description>
        <link>https://medium.com/@anastasiapristupa1805?source=rss-64fb52cef70c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3c7_preqUS2Tv0tda_OzUQ.jpeg</url>
            <title>Stories by Anastasiia Pristupa on Medium</title>
            <link>https://medium.com/@anastasiapristupa1805?source=rss-64fb52cef70c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:27:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anastasiapristupa1805/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Latency in Video Delivery: From RWMutex to Channels]]></title>
            <link>https://medium.com/@anastasiapristupa1805/latency-in-video-delivery-from-rwmutex-to-channels-7365875e636f?source=rss-64fb52cef70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7365875e636f</guid>
            <category><![CDATA[golang-mutex]]></category>
            <category><![CDATA[golang-concurrency]]></category>
            <category><![CDATA[golang-channel]]></category>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Anastasiia Pristupa]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 09:45:37 GMT</pubDate>
            <atom:updated>2026-09-01T09:49:51.316Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me start with a service that cached video content and delivered it to viewers. It lived quietly until the audience started to grow — and then packet delays showed up. The worst part wasn’t the delays themselves, but that we couldn’t put a finger on the cause. In realtime that costs you: latency is not forgiven.</p><p>The first suspect was the network. We dug into bandwidth, covered the service in metrics — and still hit a wall: the delays didn’t go anywhere.</p><p>So I decided to go radical: remove mutexes from the entire logic of writing video segments and serving them. All of it.</p><p>And to my surprise, it worked.</p><h3>What was happening under the mutex</h3><p>To make this clearer, picture a simplified version. The service writes video segments into a map — one goroutine does that. Another one takes them out and hands them to the client. And all of it is, of course, closed off by a mutex.</p><p>A segment doesn’t arrive in one piece: it consists of chunks, they are appended one by one in a loop, and the reader picks them up as they appear. Notification was handled by a separate goroutine: the writer sent it a “chunk written” event, it fanned the event out to subscribers, and they went to the map for the data. I wrote about how segments and the chunks inside them are structured in a neighbouring article — <a href="https://medium.com/@anastasiapristupa1805/from-20-seconds-down-to-two-how-low-latency-hls-and-dash-work-6d3cba09cf42?sharedUserId=anastasiapristupa1805">the one on low latency HLS and DASH</a>— so I won’t repeat it here.</p><pre>type chunk struct {<br>    mu   sync.RWMutex // every chunk has its own lock<br>    data []byte<br>}<br><br>func (ch *chunk) read() []byte {<br>    ch.mu.RLock()<br>    defer ch.mu.RUnlock()<br>    return ch.data<br>}<br><br>type cache struct {<br>    mu       sync.RWMutex          // guards the chunk lists only<br>    segments map[string][]*chunk<br>    subs     map[string][]chan struct{}<br><br>    events chan string // writer -&gt; notifier<br>}<br><br>// writer: the event goes out once the chunk is complete<br>func (c *cache) write(segID string, incoming &lt;-chan []byte) {<br>    for data := range incoming {<br>        ch := &amp;chunk{data: data}<br><br>        c.mu.Lock()<br>        c.segments[segID] = append(c.segments[segID], ch)<br>        c.mu.Unlock()<br><br>        c.events &lt;- segID<br>    }<br>}<br><br>// notifier<br>func (c *cache) notifier() {<br>    for segID := range c.events {<br>        c.mu.RLock()<br>        subs := c.subs[segID]<br>        c.mu.RUnlock()<br><br>        for _, sub := range subs {<br>            select {<br>            case sub &lt;- struct{}{}:<br>            default:<br>            }<br>        }<br>    }<br>}<br><br>// reader<br>func (c *cache) serve(segID string, w io.Writer) {<br>    updates := c.subscribe(segID)<br>    sent := 0<br>    for range updates {<br>        c.mu.RLock()<br>        chunks := c.segments[segID]<br>        c.mu.RUnlock()<br><br>        for ; sent &lt; len(chunks); sent++ {<br>            w.Write(chunks[sent].read()) // RLock on the freshest chunk<br>        }<br>    }<br>}<br><br>go c.notifier()<br>go c.write(segID, incoming)<br><br>for _, viewer := range viewers {<br>    go c.serve(segID, viewer)<br>}</pre><h3>What’s inside RWMutex</h3><p>To understand where the time goes, it’s worth looking inside. RWMutex is simpler than it seems:</p><pre>type RWMutex struct {<br>    w           Mutex        // queue between writers<br>    writerSem   uint32       // the writer sleeps here<br>    readerSem   uint32       // readers sleep here<br>    readerCount atomic.Int32 // how many readers are inside<br>    readerWait  atomic.Int32 // how many the writer is still waiting for<br>}</pre><p>The whole mechanism rests on a single counter.</p><p>RLock is an atomic increment of readerCount. If the value is positive, there is no writer: the reader moves on, blocking nothing.</p><p>Lock does a trick. It subtracts a huge constant (1&lt;&lt;30) from readerCount and drives the counter negative. For new readers, a negative value is the flag &quot;a writer has arrived&quot;: they don&#39;t enter, they go to sleep on readerSem. The writer itself waits on writerSem until the readers that were already inside leave.</p><p>Unlock adds the constant back and wakes the sleepers — all of them at once.</p><p>This is usually where the classic trouble comes from: while the writer waits for Lock, new readers don&#39;t get in and delivery stalls. We didn&#39;t have that — our readers don&#39;t sit on the lock permanently, they sleep on their channels and take RLock only on an event, for a very short time.</p><p>The second one, though, is directly relevant to us.</p><p><strong>readerCount is one variable for everybody.</strong> However many readers there are, the counter is shared. There is no per-core sharding inside RWMutex. I did copy the data out from under the lock — but what we hit was not the data, it was the synchronisation itself.</p><p>To see why that becomes a wall, we have to go one level down.</p><h3>A bit about the hardware</h3><h4><strong>RLock is not a read, it&#39;s a write.</strong></h4><p>Inside RLock there is an atomic increment of readerCount — on x86 that&#39;s the LOCK XADD instruction. An atomic read-modify-write, which means a real write to memory. Two RLock calls are, as far as the hardware is concerned, two competing writes to the same variable — even if we honestly only read the data under the lock. RUnlock is the same kind of atomic decrement. That&#39;s two writes to a shared cell per read.</p><h4>Why writing to one cell is expensive.</h4><p>A core doesn’t work with memory directly — only through its cache, and the smallest unit of exchange there is a 64-byte cache line. To perform an atomic RMW, the core has to take that line into exclusive ownership: copies on all the other cores are invalidated.</p><p>Then comes the main part. Core B wants the same counter — now it takes the line exclusively, and core A’s copy is invalidated. Core C does the same. The line starts bouncing between cores across the interconnect.</p><p>The order of magnitude looks roughly like this: a hit in the core’s own L1 is about a nanosecond, an uncontended atomic operation is single-digit to tens of nanoseconds, and pulling the line away from a neighbouring core is already tens to hundreds. Across sockets, worse.</p><p><strong>The takeaway worth keeping in mind.</strong> Readers are logically parallel, but at the hardware level they line up in a queue — not for the lock, but for the cache line. And the more cores take part, the worse it gets: with a heavy read share on a many-core machine, RWMutex can genuinely lose to a plain Mutex. That&#39;s not my conclusion — it&#39;s a <a href="https://github.com/golang/go/issues/17973">known problem</a> with an open issue in Go.</p><h3>A lock per chunk, and false sharing</h3><p>Back to what you can see in the code: every chunk has its own mutex, and the shared cache lock only guards the lists.</p><p>You’d think splitting the lock is exactly the cure: different chunks don’t get in each other’s way. But viewers don’t read different chunks — they read the same one, the freshest. The event arrives, the whole wave goes into a single object, which means into a single readerCount. So the contention is still there, it&#39;s just narrowed down to a bottleneck one chunk wide.</p><p>And false sharing gets layered on top of that.</p><p>The mechanism is the same as above, only the participants differ. Chunks lie next to each other — in a slice, in neighbouring allocations — so the mutexes of two or three adjacent chunks happily end up in the same cache line. Core A takes RLock on chunk N and pulls the line into exclusive ownership. On core B, which is working with chunk N+1 at that moment, the copy is invalidated — even though these two locks have nothing to do with each other.</p><p>This is the nastiest one of the lot. The contention is real, but it isn’t in the code: the block profile will show you nothing, because as far as sync is concerned nobody waited for anybody. Formally everything is fine — every lock is free.</p><p>The cure is padding: you pad the chunk out to the size of a cache line so that neighbours don’t share it.</p><pre>type chunk struct {<br>    mu   sync.RWMutex<br>    data []byte<br>    _    [64]byte // padding: so a neighbour doesn&#39;t land in the same line<br>}</pre><p>Martin Thompson has a detailed write-up with measurements and padding variants — <a href="https://mechanical-sympathy.blogspot.com/2011/07/false-sharing.html">Mechanical Sympathy: False Sharing</a>.</p><p>You pay for it with memory on every chunk — and this is the point where it’s worth stopping and asking yourself whether it wouldn’t be easier to remove the lock altogether.</p><h3>Rewriting it onto channels</h3><p>The idea was simple: state should belong to a single goroutine. The map didn’t go anywhere — it’s just that only run() goes to it now, and everyone else talks to it with messages. The lock isn&#39;t needed in this scheme not because we optimised it away, but because there is nothing left to guard: there is no concurrent access.</p><pre>type chunk struct {<br>    segID string<br>    data  []byte<br>}<br><br>type subscription struct {<br>    segID string<br>    ch    chan *chunk<br>}<br><br>type hub struct {<br>    subs map[string][]chan *chunk // touched only by run()<br><br>    join   chan subscription<br>    leave  chan subscription<br>    chunks chan *chunk<br>}<br><br>func (h *hub) run() {<br>    for {<br>        select {<br>        case s := &lt;-h.join:<br>            h.subs[s.segID] = append(h.subs[s.segID], s.ch)<br><br>        case s := &lt;-h.leave:<br>            h.remove(s)<br><br>        case c := &lt;-h.chunks:<br>            h.broadcast(c)<br>        }<br>    }<br>}<br><br>// called only from run(), so the map can be touched without a lock<br>func (h *hub) broadcast(c *chunk) {<br>    for _, sub := range h.subs[c.segID] {<br>        go func(sub chan *chunk) {<br>            select {<br>            case sub &lt;- c:<br>            case &lt;-time.After(2 * time.Second):<br>                // didn&#39;t take it within two seconds — drop it<br>            }<br>        }(sub)<br>    }<br>}<br><br>func (h *hub) handleViewer(w http.ResponseWriter, r *http.Request) {<br>    sub := subscription{segID: segID(r), ch: make(chan *chunk, 8)}<br><br>    h.join &lt;- sub<br>    defer func() { h.leave &lt;- sub }()<br><br>    for {<br>        select {<br>        case c := &lt;-sub.ch:<br>            w.Write(c.data)<br>        case &lt;-r.Context().Done():<br>            return // the viewer is gone<br>        }<br>    }<br>}</pre><p>Three functions, each with its own loop. run() owns the state and handles events one at a time. broadcast() lays the incoming chunk out into the subscribers&#39; channels — and since it&#39;s only ever called from run(), the map is still in the hands of one goroutine. handleViewer() runs separately for each viewer: it creates its channel, registers with the hub and writes into the connection for as long as it&#39;s alive. You don&#39;t need to start a goroutine for that — net/http already calls the handler in one.</p><p>Writing to the network moved out of the shared path and into a personal goroutine, so nobody waits for anybody.</p><p>The hot path also lost its atomic operations on shared counters — and with them both readerCount and mutexes sitting next to each other in one cache line.</p><p>But that’s not even the main thing. select with a timeout is a place where you can <strong>refuse</strong> to do the work. A viewer who didn&#39;t take the chunk within two seconds loses it, and that doesn&#39;t affect anyone else: every send lives in its own goroutine. In the mutex version there simply was no such place — there you could only wait.</p><h3>The bottom line</h3><p>Honestly, I never proved the lock was the culprit. Maybe it was contention on readerCount, maybe false sharing between adjacent chunks, maybe something else entirely.</p><p>But in the new scheme that question simply stopped existing. There is no shared memory on the hot path anymore: the state belongs to one goroutine, everyone else talks to it with messages. There is nothing left to hit.</p><p>And the drop, which in the old scheme would have looked like a failure, became a deliberate choice. For realtime it’s the right one: a chunk delivered late is already dead — better to lose it than to hold up the stream for everyone else.</p><p>That’s how I got to Rob Pike’s well-known line: “Don’t communicate by sharing memory; share memory by communicating.” I used to just know it. Now I know it from practice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7365875e636f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From 20 Seconds Down to Two: How Low Latency HLS and DASH Work]]></title>
            <link>https://medium.com/@anastasiapristupa1805/from-20-seconds-down-to-two-how-low-latency-hls-and-dash-work-6d3cba09cf42?source=rss-64fb52cef70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d3cba09cf42</guid>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[low-latency-hls]]></category>
            <category><![CDATA[low-latency-streaming]]></category>
            <category><![CDATA[low-latency]]></category>
            <category><![CDATA[low-latency-dash]]></category>
            <dc:creator><![CDATA[Anastasiia Pristupa]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 16:24:21 GMT</pubDate>
            <atom:updated>2026-08-02T16:25:53.403Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever watched football online, you know the moment: your neighbour behind the wall yells “GOOOAL” while the ball is still in midfield on your screen. Or the stream chat is discussing something you’ll see about twenty seconds later.</p><p>That’s how regular HLS and DASH work: video is cut into segments of a few seconds each, and until a segment is fully written, you can’t download it. Add the player’s buffer on top, and you end up 20–30 seconds behind real time.</p><p>In 2019 the industry started tackling this seriously: Apple released Low Latency HLS, and the DASH Industry Forum published low-latency modes for DASH. Both approaches bring latency down to 2–4 seconds, but they do it differently. Let’s look at what changes.</p><h4>DASH</h4><p>For a player to know how to play a DASH stream, we have to give it a manifest that spells out the rules. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*pghg53SwArh7UW7rdctU1g.png" /></figure><p>What matters here:</p><p>type=&quot;dynamic&quot; — this is live, not VOD.</p><p>minimumUpdatePeriod=&quot;PT6S&quot; — the player re-requests the manifest every 6 seconds to learn about new segments.</p><p>minBufferTime=&quot;PT12S&quot; — how many seconds of content the player must accumulate before it starts playing. It&#39;s protection against stalls: if the network dips, there&#39;s a reserve. But we pay for that reserve with latency.</p><p>duration=&quot;540000&quot; with timescale=&quot;90000&quot; — segment duration, 6 seconds.</p><p>media=&quot;$RepresentationID$/seg-$Number$.m4s&quot; — the template the player uses to build segment URLs. It substitutes the quality ID and the segment number and gets 1080p/seg-42.m4s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3AyxlBwqJjpt6Srs6XeJA.png" /></figure><p>And here we see the problem: while a segment is being written, we can’t download it, and we get at least a 6-second delay in the viewer’s player.</p><h4>Low Latency DASH</h4><p>Now let’s look at how this limitation was worked around in Low Latency DASH. The segment is cut into CMAF chunks of 200–500 ms, and they’re handed to the player as they become ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*pK_yP2ZkHjLW-aDeLIkAAg.png" /></figure><p>&lt;ServiceDescription&gt; with &lt;Latency&gt; — a target latency of 1.5 seconds and an acceptable range from 0.8 to 3 seconds.</p><p>&lt;PlaybackRate min=&quot;0.96&quot; max=&quot;1.04&quot;&gt; — the player may slightly speed up or slow down playback to stay at the target latency.</p><p>availabilityTimeOffset=&quot;1.8&quot; — the segment becomes available 1.8 seconds before it&#39;s finished. This is exactly what allows the player to request a file that isn&#39;t ready yet.</p><p>availabilityTimeComplete=&quot;false&quot; — states outright: the segment is served incomplete, as it&#39;s being written.</p><p>minBufferTime=&quot;PT1S&quot; — the buffer is cut down to one second: chunks arrive often and small, there&#39;s nothing to accumulate.</p><p>The other numbers changed too: segments are now 2 seconds instead of 6, and the manifest is re-requested every 2 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bmeoFPfqe5kvObHpMLZdg.png" /></figure><p><strong>How can a player download a file that isn’t written yet?</strong></p><p>When the player sends a GET for a segment that isn’t finished, the server responds not with Content-Length but with Transfer-Encoding: chunked — meaning &quot;I don&#39;t know the final size, I&#39;ll send it in portions&quot;. And as each chunk is written, the server immediately pushes it into that same open response.</p><p>A chunk on its own is a header with metadata plus the data itself. The player can play it without having the rest of the segment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTGKcVoGwMs9p8tqg_Uouw.png" /></figure><p>So we can see this significantly reduces latency.</p><h4>HLS</h4><p>The HLS playlist looks different — it’s not XML but a text file with directives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*_G1gKpjkz_AkVn_aWxWhNQ.png" /></figure><p>#EXT-X-TARGETDURATION:6 — maximum segment duration, 6 seconds. The player uses it to decide how often to re-request the playlist.</p><p>#EXT-X-MEDIA-SEQUENCE:142 — the number of the first segment in the list. It grows with each playlist update, and old segments drop out of the window.</p><p>#EXTINF:6.000, — the duration of a specific segment, with its filename on the next line. Unlike DASH, segments here are listed explicitly rather than assembled from a template.</p><h4>Low Latency HLS</h4><p>Apple took a different route from DASH: instead of serving an unfinished segment in pieces, they added the pieces themselves to the playlist — as separate entries with their own URIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*zfF0vwNNzUtnXFTuHhwuyw.png" /></figure><p>#EXT-X-PART-INF:PART-TARGET=0.500 — declares that segments are cut into parts of 0.5 seconds.</p><p>#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES — the server supports blocking requests: the player asks for the next part, and the server holds the request open until it appears. No need to poll the playlist in a loop.</p><p>PART-HOLD-BACK=1.5 — how far the player should stay behind the live edge. This is the target latency.</p><p>#EXT-X-PART:DURATION=0.500,URI=&quot;seg-144.1.m4s&quot; — parts of segment 144, which isn&#39;t finished yet. Each is available as its own file, and the player takes them as they appear.</p><p>#EXT-X-PRELOAD-HINT — the server announces the URI of the next part in advance. The player requests it before it&#39;s ready and gets the response the moment it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcyLpG4fia-w00Q3SeEunA.png" /></figure><p>Here we can see that instead of a single GET request, as in DASH, there are several — one per chunk.</p><p>And here’s the latency diagram for comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjXIxrvizWmyxdgFpI-lew.png" /></figure><h4>Summary</h4><p>In the end both give roughly the same latency — 2–4 seconds instead of twenty-plus. In practice you have to support both formats, but note that the difference between LL-HLS and LL-DASH on the server side is only in how you build the playlist and how you serve those chunks — the chunks themselves are identical in HLS and DASH.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d3cba09cf42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebRTC or “Why Video Streaming Is Always Expensive?”]]></title>
            <link>https://medium.com/@anastasiapristupa1805/webrtc-or-why-video-streaming-is-always-expensive-fb80a2501ac3?source=rss-64fb52cef70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb80a2501ac3</guid>
            <category><![CDATA[web-video-streaming]]></category>
            <category><![CDATA[video-streaming-service]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[Anastasiia Pristupa]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 20:25:06 GMT</pubDate>
            <atom:updated>2026-07-08T20:25:06.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpRLc51A2qO6l-k6wW_aww.png" /></figure><p>In short: WebRTC is a technology for establishing peer-to-peer connections between two clients. It’s most commonly used in video streaming where speed is crucial and the loss of a few packets is not critical.</p><p>For example, Zoom and Google Meet use WebRTC. You could use TCP, but packet transmission speed would drop — you probably already know the difference between UDP and TCP, so I won’t teach you that. The real magic lies in how the connection is established between clients.</p><p>Let’s get to the point: Yes, when you’re talking on Zoom, you’re establishing a direct connection and streaming your video from one computer to another, bypassing any servers (in about 80% of cases). That’s why the latency is so low. The question is: How do you know how to connect to the other peer?</p><p>To achieve this, we generate an SDP offer (Session Description Protocol) and send it to a server, which forwards it to the other peer. The offer contains information about our IP (usually IPv4), supported video and audio codecs. The other client accepts our SDP and forms their own response SDP based on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*2py38_OiuJb2jv3JlZkSMA.png" /></figure><p>After peers exchange their data, they can attempt to establish a connection, and this is where ICE (Interactive Connectivity Establishment) comes into play. Let’s consider a simple case — when both clients have public IPs or are behind the same router using IP address translation (NAT). To discover ICE candidates, peers request their external IP address and form ICE candidates, which they then send to the other peer via a server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*PdLdupnU9nOztLjsK34AWg.png" /></figure><p>If you’re not behind NAT, you don’t even need STUN — you already know your external IP. But there’s still a bit of a mystery: when we send our external IP to the other peer, that IP doesn’t belong only to us. We’re behind NAT, so the stream reaches the router — but how does it know which computer to forward traffic to?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*6rFWPI1JvLM96triLCKkRQ.png" /></figure><p>Don’t worry — the NAT keeps an internal port mapping table (external port = internal IP and port). STUN helps by detecting this mapping and sending the external IP and port back to the client, which then passes it to the other peer.</p><p>Now we approach another issue: What if the client is behind two routers (double NAT)? In this case, we’ll get an external IP and port, give it to the other peer, and when they try to connect, the connection fails at the second router.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*iqh8JjnoXeA6tS_Yolh7AA.png" /></figure><p>Exactly. STUN can see where traffic came from and log the IP and port, but it can’t see past the router.</p><p>That’s why TURN servers were invented! Hang in there, folks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*WcXa3fFHaNdV_oFWiPBD1w.png" /></figure><p>About 20% of clients are in this tricky situation and can’t use direct peer-to-peer connections — so they rely on data relayed through a TURN server. How is the ICE candidate formed in this case?</p><p>The TURN server, which also performs STUN functionality, sends not only the external IP but also its own IP and port. The client then shares the TURN server’s IP as its own with the other peer. The second client also connects to the TURN server and receives the same info. Now both peers have ICE candidates that point to the TURN server.</p><p>They try to connect using the given candidates (let’s skip the protocols checking for security). If a direct connection fails, data is transmitted through the TURN server.</p><p>This is all. Thank you for reading to the end!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb80a2501ac3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>