network

115
Mobile Networks Understanding communication layer for web and mobile

Upload: ynon-perek

Post on 15-Jan-2015

599 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Network

Mobile NetworksUnderstanding communication layer for web and mobile

Page 2: Network

Agenda• Networking basics

• How mobile networks work

• Optimising for mobile networks

• Other HTTP/1.x optimisations

• Browser APIs and protocols: XHR, SSE, WebSockets

Page 3: Network

Why Do You Care ?

• How does network affect your application?

Page 4: Network

Why Do You Care ?

• Speed: How fast can I deliver content to a user ?

• Battery: What network operations affect battery life ?

• Cost: Is connection metered ?

Page 5: Network

Let’s start with “speed”

47% of consumers expect a web page to load in 2

seconds or less.“ ”

Page 6: Network

Let’s start with “speed”

73% of mobile internet users say

that they’ve encountered a website

that was too slow to load.“ ”

Page 7: Network

Let’s start with “speed”

Just One Second Delay In Page-Load Can Cause

7% Loss In Customer Conversions“ ”

Page 8: Network

How load times affect conversion

• Glasses direct measured

Page 9: Network

How load times affect conversion• Wallmart measured

Page 10: Network

How load times affect conversion

• Strangeloop measured

Page 11: Network

How load times affect conversion

• Google measured

Type Of Delay Delay (ms) Duration (weeks) Impact

Pre Header 50 4 -

Pre Header 100 4 -0.2%

Post Header 200 6 -0.59%

Post Header 400 6 -0.59%

Page 12: Network

Speed: You should care• Load times affects:

• Bounce rate

• Time on site

• Conversion

• Satisfaction

Page 13: Network

Q & A

Page 14: Network

Network speed

Page 15: Network

Bandwidth is growing

Page 16: Network

Bandwidth Considerations

• For most applications, bandwidth is not an issue

• HSPA+ (2008) :

• Up to 84Mbit/s down link

• Up to 10.8Mbit/s up link

Page 17: Network

Latency, on the other hand…• Latency:

• is bound by the speed of light

• is not expected to grow dramatically in coming years

• Has drastic effect on applications that transfer small amounts of data

Page 18: Network

Latency vs. Bandwidth

Page 19: Network

Latency Upper Bound

• Latency is bound by the speed of light

Route Distance Time: light in vacuum

Time: light in finer RTT

New York to London 5,585km 19ms 28ms 56ms

New York to Sidney 15,998km 53ms 80ms 160ms

Page 20: Network

In practice

• Latency is much higher

• Distance is not air line

• Affected by network delays

Page 21: Network

Demo

• Checking latency with traceroute

• Discussion: How would you reduce latency?

Page 22: Network

Q & A

Page 23: Network

Transmission Control Protocol (TCP)

Page 24: Network

TCP/IP Network Basics

• IP provides host-to-host routing

• TCP provides application-to-application reliable channel

Page 25: Network

TCP/IP Network Basics

Page 26: Network

TCP and network speed

• TCP Handshake

• TCP congestion control

• Head of line blocking

Page 27: Network

TCP Handshake

Page 28: Network

TCP Handshake implication

• Each new connection requires a full round trip before data can be sent

• => New TCP connections are expensive

Page 29: Network

TCP Congestion control

• When a packet is not ACKed after a retransmission interval, the host resends it

• What happens if RTT > retransmission interval ?

Page 30: Network

TCP Congestion

Host A Host B

Page 31: Network

TCP Slow Start

• cwnd variable on the server controls how many packets can be “in flight” at any given time

• Ack => cwnd++

Page 32: Network

TCP Slow Start

Ack 1

cwnd = 4

cwnd = 5

Page 33: Network

TCP Slow Start: Quiz

• Assuming initial cwnd = 4

• Roundtrip time 56 ms (New York -> London)

• TCP packet size is 1460 bytes

• How much time do you need to get a 64kb throughput ?

Page 34: Network

TCP Slow Start

• 65,535 / 1460 =~ 45 packets

• We need to get 45 packets in flight to reach 64kb

• Remember cwnd doubles each round trip

Page 35: Network

TCP Slow Start

• cwnd values: 4 => 8 => 16 => 32 => 64

• 4 rountrips * 56ms = 224 ms

Page 36: Network

TCP Slow Start

Page 37: Network

Q & A

Page 38: Network

Head of line blocking

• Host A sends 5 TCP packets: a1, a2, a3, a4, a5

• Packets a2-a5 reach in time

• Packet a1 dropped by an intermediate router and has to be resent

• How is your application affected?

Page 39: Network

Head of line blocking

Process Effect of head-of-line blocking

File transfer

Video chat

Music streaming

Web page

Page 40: Network

Head of line blocking

Process Effect of head-of-line blocking

File transfer None. App has nothing to do with a partial

Video chat Jitter

Music streaming It depends. Requires buffering or jitters

Web page Suffers from both HTTP and TCP HOL

Page 41: Network

TCP Optimisations: Server

• Increase cwnd

• Disable slow-start after idle

Page 42: Network

TCP Optimisations: App

• Reuse existing connections as much as possible

• Aggregate messages

• Use a CDN

• Use compression

Page 43: Network

Q & A

Page 44: Network

Mobile Networks

Page 45: Network

Types of Mobile NetworksType Applications Standards

Personal area network (PAN) Cable replacements Bluetooth, NFC

Local area network (LAN) Wireless extension of network 802.11 (WiFi)

Metropolitan area network (MAN)

Wireless inter network connectivity 802.15 (WiMax)

Wide area network (WAN) Wireless network access Cellular (UMTS, LTE,…)

Page 46: Network

WiFi Attributes

• No bandwidth or latency guarantee

• WiFi access is usually un-metered

Page 47: Network

Leveraging WiFi

• Use WiFi to download large files or stream data

• Prompt user to switch to wifi when applicable

Page 48: Network

Leveraging WiFi

• Detect WiFi or 3G:

• iOS: https://developer.apple.com/library/ios/samplecode/Reachability/Listings/Reachability_Reachability_m.html

• Android: https://gist.github.com/emil2k/5130324

Page 49: Network

Leveraging WiFi

• Adapt to variable bandwidth

• Quiz:

• What can cause bandwidth to vary?

• How does variable bandwidth affect video streaming app ?

Page 50: Network

Leveraging WiFi

• When streaming video, we need to detect best bitrate for a connection

• Quiz: How would you adapt to varying bandwidth in a video streaming app?

Page 51: Network

Adaptive Bitrate Streaming

• Encode each segment for multiple bitrates

• Netflix has over 120 different versions for each stream

Page 52: Network

Q & A

Page 53: Network

Cellular Networks

Page 54: Network

Cellular Attributes

• Varying infrastructure (generations) lead to varying bandwidth and latencies

• Battery is an issue

• Data is an issue

Page 55: Network

Mobile Gs

Generation Data Rate Latency

2G 100-400 Kbit/s 300-1,000 ms

3G 0.5-5 Mbit/s 100-500 ms

4G 1-50 Mbit/s < 100 ms

Page 56: Network

Mobile Network• What you should expect:

• Network infrastructure is changing slow

• 2G networks are still around (and will be)

• 3G networks are still around (and will be)

• 3.5G, 3.75G, 3.9G are all around

• 4G

Page 57: Network

Mobile Is Different

Page 58: Network

RRC

• Radio Resource Controller allows devices to put their radio to sleep

• It instructs a device when to speak, and when to listen

Page 59: Network

RRC State Machine

Page 60: Network

Quiz

• When listening to music, Pandora wants to know how long you listen

• Here’s what they did:

• Send entire song to user when user starts to play

• During playback, send periodic updates to Pandora server

• Describe RRC state changes

• How is battery affected ?

Page 61: Network

Periodic Updates and MobilePo

wer

Dat

a Tra

nsfe

r

Short DRX

Long DRXidle

Dat

a Tra

nsfe

r

Page 62: Network

Periodic Updates and MobilePo

wer

Dat

a Tra

nsfe

r

Short DRX

Long DRXidle

Dat

a Tra

nsfe

r

Energy tail

Page 63: Network

Periodic Updates and Mobile

• Energy tails waste power

• For Pandora: 46% of battery consumption to transfer 0.2% of total bytes

• What can Pandora do ?

Page 64: Network

Periodic Updates and Mobile

• A better solution:

• save data on client and send it all aggregated in a later time

Page 65: Network

Q & A

Page 66: Network

Routing In Cellular Network

Page 67: Network

Routing In Cellular Network

• PGW (Packet Gateway) acts like a NAT

• It assigns IP address to a mobile device

• It keeps TCP connection alive when mobile device moves

Page 68: Network

Routing In Cellular Network

• PCRF (Policy and Charging Rules Function) instructs PGW how to assign addresses

Page 69: Network

• SGW (Service Gateway) routes all data to the mobile device

• MME (Mobility Management Entity) keeps track of each device and its current cell tower

Page 70: Network

Other Considerations

• Latency is bad when device was idle

• Bandwidth is a big issue for carriers

Page 71: Network

Cellular Networks Optimisations

Page 72: Network

Save Battery

• Eliminate periodic and inefficient data transfers

• Defer non-critical requests until radio is active

• Eliminate application keep-alives

Page 73: Network

Anticipate Latency

• 3G latency 200-3,500 ms

• Decouple user interactions from network

• Burst data and return to idle

Page 74: Network

Save Bandwidth

• Consider offloading to WiFi if possible

• Cache data locally

• Always consider offline

• Plan and test for slow network

Page 75: Network

Q & A

Page 76: Network

Optimising for the web

Simple HTTP techniques to optimise mobile web access

Page 77: Network

HTTP Basics

• Verify using HTTP 1.1 and Keepalive

• Verify using GZip compression

• Can use chrome or:curl -I --compressed http://yoursite.com

Page 78: Network

CSS Sprites

Page 79: Network

Use the best image size

Page 80: Network

Avoid Redirects at all costs

• Redirects add another request but with no value

• Worst kind: Mobile Redirects

• Demo: d.co.il

Page 81: Network

Better Way: Use smart banners

• Offer to download the app from within the page

<meta name="apple-itunes-app" content="app-id=366977202">

Page 82: Network

Use caches to reduce requestsFile size doesn’t matter

Page 83: Network

Use caches to reduce requests

• HTTP 1.0 Had an Expires header:Expires: Thu, 15 Apr 2010 20:00:00 GMT

• HTTP 1.1 Added Cache-Control header:Cache-Control: max-age=315360000

Page 84: Network

HTTP 1.1 Pipelining

Page 85: Network

HTTP 1.1 Pipelining

• Send multiple requests not waiting for responses

• HOL blocking can occur

• Fewer round-trips

Page 86: Network

HTTP 1.1 Pipelining

Page 87: Network

HTTP 1.1 Pipelining

• Supported browsers:

• Android

• Opera

Page 88: Network

Optimising for Pipelining

• Make sure web server supports it (probably does)

• Serve slow (dynamic) resources from a different domain than static resources

Page 89: Network

Q & A

Page 90: Network

Browser APIs and Protocols

• XMLHttpRequest

• Server Sent Events

• Web Sockets

Page 91: Network

XHR

• XMLHttpRequest began on IE as part of MSXML

• Script data transfers via JavaScript

Page 92: Network

XHR in use

• Get partial data after initial page load

• Other uses (not optimal):

• Polling

• Resumable Upload

Page 93: Network

XHR Loading data

• Example:

• Initial page has a list of products

• User clicks on a product

• XHR is used to get product info and inject to page

Page 94: Network

XHR Code

var xhr = new XMLHttpRequest(); xhr.open('GET', 'info.json'); xhr.onload = function(e) { // handle response data if (xhr.status != 200) return; var info = JSON.parse(xhr.responseText); document.querySelector('h2').innerHTML = info.name; document.querySelector('.bio').innerHTML = info.biography; }; xhr.send();

Page 95: Network

XHR Polling

• XHR provides a simple method to get server events

• Two options:

• Interval polling

• Long polling

Page 96: Network

XHR Polling

• Quiz: In regards to mobile battery life - which polling method would you prefer ?

Page 97: Network

XHR Polling• Answer:

It depends :)Interval polling keeps radio active, but aggregates events Long polling is not a good idea in case of frequent events

Page 98: Network

XHR Upload

• Use JavaScript to slice buffer before sending

• Send small fragments in a loop

• Resend only failed fragments

Page 99: Network

XHR Upload Demo Code

while ( start < SIZE ) { var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload'); xhr.onload = function() { /* ... */ }; xhr.setRequestHeader('Content-Range', " start + '-' + end + '/' + SIZE); xhr.send(blob.slice(start, end)); start = end; end = start + BYTES_PER_CHUNK; }"

Usable JS library: resumablejs.com

Page 100: Network

Server Sent Events

Client Server

GET /events

Page 101: Network

Server Architecture

Socket Server Application Server

Client Browser

mq / db

http

Page 102: Network

Server Architecture

• Most web servers are optimised for short lived client connections (HTTP)

• Socket server is optimised for maintaining many (mostly) idle connections

Page 103: Network

SSE Protocol

• Each line starts with a data: prefix

• Can also specify other event attributes

Page 104: Network

SSE Protocol

1 data: {\n"2 data: "msg": "hello world",\n"3 data: "id": 12345\n"4 data: }\n\n"5 "

Page 105: Network

SSE Protocol

• Can specify event name

• Browser can assign different handler for each event name

1 data: {"msg": "First message"}\n\n"2 event: userlogon\n"3 data: {"username": "John123"}\n\n"4 event: update\n"5 data: {"username": "John123", "emotion": "happy"}\n\n"

Page 106: Network

Demo Code: stomp

• Demo

• Socket Server + Application Server : Mojolicious (perl)

• MQ

• Sending random text to clients

Page 107: Network

Web Sockets

• Bidirectional text and binary socket

• As close to raw socket as can get

Page 108: Network

Web Sockets Attributes

• Same origin policy

• Message oriented

Page 109: Network

WebSocket API 1 var connection = new WebSocket('ws://html5rocks.websocket.org/echo');" 2 " 3 // When the connection is open, send some data to the server" 4 connection.onopen = function () {" 5 connection.send('Ping'); // Send the message 'Ping' to the server" 6 };" 7 " 8 // Log errors" 9 connection.onerror = function (error) {"10 console.log('WebSocket Error ' + error);"11 };"12 "13 // Log messages from the server"14 connection.onmessage = function (e) {"15 console.log('Server: ' + e.data);"16 };"

Page 110: Network

WebSockets Keep In Mind

• No compression - if needed implement your own

• TLS is recommended

• For mobile: send in bursts

Page 111: Network

Socket.IO

• A WebSocket Library

• Maintains connected clients

• Includes a JS library

• Automatic fallback

Page 112: Network

Demo Code: Menotes• https://github.com/ynonp/menotes

• Note taking angular app with sockets

• Stack:

• Application server : perl (catalyst)

• Socket server : node

• Message Queue: Rabbit MQ

• Client: Angular.JS

Page 113: Network

Q & A

Page 114: Network

Thanks For Listening

• Ynon Perek

• http://ynonperek.com

[email protected]

Page 115: Network

Photos & Data From• World bandwidth (slide 15):

http://techcrunch.com/2012/08/09/akamai-global-average-broadband-speeds-up-by-25-u-s-up-29-to-6-7-mbps/

• Mobile Web (slide 76): http://www.flickr.com/photos/khawkins04/8659736133/sizes/c/

• HTTP Pipielining (slide 84): http://en.wikipedia.org/wiki/HTTP_pipelining

• Illustrations: 123rf.com