Netty from the trenches

173
Netty from the trenches June 2015 @jordi9

Transcript of Netty from the trenches

Page 1: Netty from the trenches

Netty from the trenches

June 2015@jordi9

Page 2: Netty from the trenches

Netty…?

Page 3: Netty from the trenches

Netty is an asynchronous event-driven

network application framework

for rapid development of

maintainable high performance

protocol servers & clients.

Page 4: Netty from the trenches

Netty is an asynchronous event-driven

network application framework

for rapid development of

maintainable high performance

protocol servers & clients.

Page 5: Netty from the trenches
Page 6: Netty from the trenches

Netty is a NIO client server

framework which enables quick and easy development

of network applications such

as protocol servers and clients. It

greatly simplifies and streamlines

network programming such as TCP and UDP

socket server.

Page 7: Netty from the trenches

Netty is a NIO client server

framework which enables quick and easy development

of network applications such

as protocol servers and clients. It

greatly simplifies and streamlines

network programming such as TCP and UDP

socket server.

Page 8: Netty from the trenches

Netty is a NIO client server

framework which enables quick and easy development

of network applications such

as protocol servers and clients. It

greatly simplifies and streamlines

network programming such as TCP and UDP

socket server.

Page 9: Netty from the trenches

OH, MY

Page 10: Netty from the trenches

The Freaking Basics

Page 11: Netty from the trenches

You’ve heard of:

Async apps

Page 12: Netty from the trenches

You’ve heard of:

Event driven frameworks

Page 13: Netty from the trenches

You’ve heard of:

non-blockingoperations

Page 14: Netty from the trenches

You’ve heard of:Node is cooler

because...

Page 15: Netty from the trenches

I/O

Page 16: Netty from the trenches

I/O is everywhere

Page 17: Netty from the trenches

I/O, approx:

CPU Memory

Device

Page 18: Netty from the trenches

read()

Page 19: Netty from the trenches

read()

//wait...

Page 20: Netty from the trenches

read()

//wait...

keepWorkingBro()

Page 21: Netty from the trenches

Our programBLOCKS

Page 22: Netty from the trenches

Resources WASTED

Page 23: Netty from the trenches

You know what I’m talking

about

Page 24: Netty from the trenches

WebserverRequest

Database

//wait...

Page 25: Netty from the trenches

OH, Parallelism!

Page 26: Netty from the trenches

new Thread();

Page 27: Netty from the trenches

WebserverRequest

Database

//wait...

Page 28: Netty from the trenches

WebserverRequest

Database

//wait...

Request

Database

//wait...

Page 29: Netty from the trenches

WebserverRequest

Database

//wait...

Request

Database

//wait...

Request

Database

//wait...

Page 30: Netty from the trenches

A mess

Page 31: Netty from the trenches

We can do better

Page 32: Netty from the trenches

read()

Page 33: Netty from the trenches

read()

keepWorkingBro()

Page 34: Netty from the trenches

read()

keepWorkingBro()

//I’m //done!

Page 35: Netty from the trenches

You (kinda) did this:

Listeners

Page 36: Netty from the trenches

You (kinda) did this:

Guava’s EventBus

Page 37: Netty from the trenches

You (kinda) did this:

Javascript callbacks

Page 38: Netty from the trenches

Hollywood principle

“Don’t call us,we’ll call you”

Page 39: Netty from the trenches

Keep working, instead of

waiting

Page 40: Netty from the trenches

Hi, Async I/O

Page 41: Netty from the trenches

NIOwith Java

Page 42: Netty from the trenches

java.nio

Page 43: Netty from the trenches

since 1.4, 2002java.nio

Page 44: Netty from the trenches

since 1.7: NIO2more goodies

Page 45: Netty from the trenches

Hi, Complexity

Page 46: Netty from the trenches

Netty to the Rescue

Page 47: Netty from the trenches

Built on top of:

java.nio

Page 48: Netty from the trenches

Built on top of:

java.net

Page 49: Netty from the trenches

Dependecy-haters:

Just JDK 1.6+

Page 50: Netty from the trenches

ONEbig difference

Page 51: Netty from the trenches

All Netty APIsare async

Page 52: Netty from the trenches

It’s can be one more tool!

Page 53: Netty from the trenches

What the hell is Netty for?

Page 54: Netty from the trenches

Think...

Page 55: Netty from the trenches

HTTP everywhere

Page 56: Netty from the trenches

Really BRO?

Page 57: Netty from the trenches

Maybe, you’re trying to

implement a protocol

Page 58: Netty from the trenches

Finally, hello Netty!

Page 59: Netty from the trenches

Netty:

Tool to implement network

applications

Page 60: Netty from the trenches

Netty:

Both from server and client side

Page 61: Netty from the trenches

Netty:

NIO everywhere

Page 62: Netty from the trenches

Why Netty?

Page 63: Netty from the trenches

Netty has been designed carefully

with the experiences

earned from the implementation of a lot of protocols

such as FTP, SMTP, HTTP, and

various binary and text-based legacy

protocols. As a result, Netty has

succeeded to find a way to achieve

ease of development, performance, stability, and

flexibility without a compromise

Page 64: Netty from the trenches

Netty has been designed carefully

with the experiences

earned from the implementation of a lot of protocols

such as FTP, SMTP, HTTP, and

various binary and text-based legacy

protocols. As a result, Netty has

succeeded to find a way to achieve

ease of development, performance, stability, and

flexibility without a compromise

Page 65: Netty from the trenches

Netty has been designed carefully

with the experiences

earned from the implementation of a lot of protocols

such as FTP, SMTP, HTTP, and

various binary and text-based legacy

protocols. As a result, Netty has

succeeded to find a way to achieve...

Page 66: Netty from the trenches

Ease of development

Page 67: Netty from the trenches

Performance

Page 68: Netty from the trenches

Stability

Page 69: Netty from the trenches

Flexibility

Page 70: Netty from the trenches

Without a compromise

Page 71: Netty from the trenches

IT’S TRUE

Page 72: Netty from the trenches

“Implementing a protocol”

NOT THAT HARD

Page 73: Netty from the trenches

Most common protocols:

out-of-the-box

Page 74: Netty from the trenches

Boring Protocols:

HTTP

Page 75: Netty from the trenches

Boring Protocols:

SSL

Page 76: Netty from the trenches

Boring Protocols:

UDP

Page 77: Netty from the trenches

Cooler Protocols:

SPDY

Page 78: Netty from the trenches

Cooler Protocols:

HTTP/2

Page 79: Netty from the trenches

Cooler Protocols:

Protobuf

Page 80: Netty from the trenches

Even Protocols:

Memcache

Page 81: Netty from the trenches

Not only I/O

Page 82: Netty from the trenches

Powerful Thread model

Page 83: Netty from the trenches

But, where’s the downside?

Page 84: Netty from the trenches

Downers:

Constant API changes*

Page 85: Netty from the trenches

Downers:

Constant API changes*

*For the best

Page 86: Netty from the trenches

Downers:

Learning curve...

Page 87: Netty from the trenches

Downers:

Learning curve...

Buy Netty in Action :P

Page 88: Netty from the trenches

Downers:

Join the mailing list

Page 89: Netty from the trenches

Downers:

Join the mailing list

You’ll see how STUPID you are

Page 90: Netty from the trenches

Downers:

Join the mailing list

But you’ll learn ALOT ;)

Page 91: Netty from the trenches

Netty,The Code

Page 92: Netty from the trenches

Daytime Protocol

Page 93: Netty from the trenches
Page 94: Netty from the trenches

TheServer

Page 95: Netty from the trenches

class SimpleDaytimeHandler extends ChannelInboundHandlerAdapter {

}

The Hand e

Page 96: Netty from the trenches

class SimpleDaytimeHandler extends ChannelInboundHandlerAdapter {

// Handler = Business Logic

}

The Hand e

Page 97: Netty from the trenches

class SimpleDaytimeHandler extends ChannelInboundHandlerAdapter {

// ChannelHandler: handles operations // for that Channel, duh

}

The Hand e

Page 98: Netty from the trenches

class SimpleDaytimeHandler extends ChannelInboundHandlerAdapter {

// Inbound handler: incoming traffic, // dispatch events to next handler// If we have inbound...

}

The Hand e

Page 99: Netty from the trenches

class SimpleDaytimeHandler extends ChannelInboundHandlerAdapter {

// Outbound handler: same, but the // other direction. Yeah, there’s some// flow between Handlers (eg: Pipeline)

}

The Hand e

Page 100: Netty from the trenches

class SimpleDaytimeHandler extends ChannelInboundHandlerAdapter {

// Inbound + Outbound...

}

The Hand e

Page 101: Netty from the trenches

class SimpleDaytimeHandler extends ChannelInboundHandlerAdapter {

// Inbound + Outbound..

// 5.0: DEPRECATED!// [NOTE: Insert a grumpy cat here]

}

The Hand e

Page 102: Netty from the trenches

Hand e me hod

Page 103: Netty from the trenches

@Overridepublic void channelRead( ChannelHandlerContext ctx, Object msg) {

// Will trigger when we receive // some data

}

Hand e me hod

Page 104: Netty from the trenches

@Overridepublic void channelActive( ChannelHandlerContext ctx, Object msg) {

// Will a Channel is opened, this // method will be called

}

Hand e me hod

Page 105: Netty from the trenches

@Overridepublic void channelActive(ChannelHandlerContext ctx, Object msg) {

String date = DATE_TIME.print(new DateTime()); // Get the date

}

Hand e wo

Page 106: Netty from the trenches

@Overridepublic void channelActive(ChannelHandlerContext ctx, Object msg) {

String date = DATE_TIME.print(new DateTime()); ctx.writeAndFlush(ByteBufUtil.encodeString( ctx.alloc(), CharBuffer.wrap(date), CharsetUtil.US_ASCII));

}

Hand e wo

Page 107: Netty from the trenches

It’s clear, right? :D

Page 108: Netty from the trenches

Network standard way of

working?byte[]

Page 109: Netty from the trenches

You said this was fun?

Page 110: Netty from the trenches

MeetByteBuf

ByteBufUtil

Page 111: Netty from the trenches

@Overridepublic void channelActive(ChannelHandlerContext ctx, Object msg) {

String date = DATE_TIME.print(new DateTime()); ctx.writeAndFlush(ByteBufUtil.encodeString( ctx.alloc(), CharBuffer.wrap(date), CharsetUtil.US_ASCII)); // We need to encode the String

}

Hand e wo

Page 112: Netty from the trenches

@Overridepublic void channelActive(ChannelHandlerContext ctx, Object msg) {

String date = DATE_TIME.print(new DateTime()); ctx.writeAndFlush(ByteBufUtil.encodeString( ctx.alloc(), CharBuffer.wrap(date), CharsetUtil.US_ASCII)); // We allocate some space // +Netty: Keeps internal pools

}

Hand e wo

Page 113: Netty from the trenches

@Overridepublic void channelActive(ChannelHandlerContext ctx, Object msg) {

String date = DATE_TIME.print(new DateTime()); ctx.writeAndFlush(ByteBufUtil.encodeString( ctx.alloc(), CharBuffer.wrap(date), CharsetUtil.US_ASCII)); // Write the message // Request to actually flush the data // back to the Channel

}

Hand e wo

Page 114: Netty from the trenches

We have our Handler in place

Page 115: Netty from the trenches

Let’s Bootstrap the server

Page 116: Netty from the trenches

Ma n asspublic class DaytimeServer { void run() throws Exception { // fun stuff }

public static void main(String[] args) throws Exception { DaytimeServer daytimeServer = new DaytimeServer(); daytimeServer.run(); }

}

Page 117: Netty from the trenches

java -jar daytimeserver-fat.jar

Page 118: Netty from the trenches

un()EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();

Page 119: Netty from the trenches

E en LoopG oup

Netty’s way to handle threads

Page 120: Netty from the trenches

E en LoopG oupEventLoopGroup contains someEventLoops

Page 121: Netty from the trenches

E en LoopEventLoop

handles manyChannels

Page 122: Netty from the trenches

About to die BRO?

Page 123: Netty from the trenches

E en LoopG oup

E en Loop

hannehanne

hannehanne

hannehanne

hannehanne

hannehanne

hannehanne

hannehanne

hannehanne

E en Loop

Page 124: Netty from the trenches

E en LoopG oup

E en Loop

hannehanne

hannehanne

hannehanne

hannehanne

hannehanne

hannehanne

hannehanne

hannehanne

E en Loop

Page 125: Netty from the trenches

This immutable assignment is

the key

Page 126: Netty from the trenches

un()EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();

Page 127: Netty from the trenches

un()EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();

// Boss group accepts connections// Work group handles the work

Page 128: Netty from the trenches

Se e Boo s apServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .localAddress(8080) .option(ChannelOption.SO_BACKLOG, 100)

Page 129: Netty from the trenches

Se e Boo s apServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .localAddress(8080) .option(ChannelOption.SO_BACKLOG, 100)

// We assign both event loops

Page 130: Netty from the trenches

Se e Boo s apServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .localAddress(8080) .option(ChannelOption.SO_BACKLOG, 100)

// We use a ServerSocketChannel// to accept TCP/IP connections// as the RFC says

Page 131: Netty from the trenches

Se e Boo s apServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .localAddress(8080) .option(ChannelOption.SO_BACKLOG, 100)

// Simply bind the local address

Page 132: Netty from the trenches

Se e Boo s apServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .localAddress(8080) .option(ChannelOption.SO_BACKLOG, 100)

// Set some Socket options... why not?// Just remember: This is not handled// by Netty or the JVM, it’s the OS

Page 133: Netty from the trenches

We’re almost there!

Page 134: Netty from the trenches

hanne P pe neb.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new SimpleDaytimeHandler()); }});

Page 135: Netty from the trenches

hanne P pe neb.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new SimpleDaytimeHandler()); }});

// ChannelPipeline to define your// application workflow

Page 136: Netty from the trenches

hanne P pe neb.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new SimpleDaytimeHandler()); }});

// Append our handlers// ProTip: use LoggingHandler to// understand Netty

Page 137: Netty from the trenches

hanne P pe neb.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new SimpleDaytimeHandler()); }});

// Finally, we add our handler

Page 138: Netty from the trenches

RUN!b.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new SimpleDaytimeHandler()); }});

ChannelFuture f = b.bind().sync();f.channel().closeFuture().sync();

// It works!

Page 139: Netty from the trenches

.I.A.Futures

ByteBuf APICodecs

TransportsZero-file-copy

Page 140: Netty from the trenches

We can also create

client code

Page 141: Netty from the trenches

Real lifeInsights

Page 142: Netty from the trenches

We’re using Netty for Real-Time Bidding

Page 143: Netty from the trenches

Boo s ap

Page 144: Netty from the trenches

Tons o op ons

Page 145: Netty from the trenches

Don’t be afraid of “low-level”

Page 146: Netty from the trenches

Ta HTTP

Page 147: Netty from the trenches

Explore what’s inside Netty

Page 148: Netty from the trenches

Integrate things you love. In my

case: GUICE

Page 149: Netty from the trenches

Gu e@InjectDaytimeService(Provider<DaytimeServer> daytimeProvider) {}

b.childHandler(() → { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(daytimeProvider.get());});

// Inject a Provider<T> and get // instances

Page 150: Netty from the trenches

But… is Netty FAST?

Page 151: Netty from the trenches

2ms*

Page 152: Netty from the trenches

* Without network latency

2ms*

Page 153: Netty from the trenches

Yah but… what volume are you talking about?

Page 154: Netty from the trenches

+10k QPS

Page 155: Netty from the trenches

1 node*+3k QPS

*Fou 2.79GHz In e Pen um Xeon P o esso s, 7.5GB RAM

Page 156: Netty from the trenches

But, is this ALOT or not?

Page 157: Netty from the trenches

Parse example

http://blog.parse.com/learn/how-we-moved-our-api-from-ruby-to-go-and-saved-our-sanity/

(From Ruby to Go) A year and a half in, at the end of 2012, we had 200 API servers running on m1.xlarge instance types with 24 unicorn workers per instance. This was to serve 3000 requests per second for 60,000 mobile apps

Page 158: Netty from the trenches

We have 16 nodes! 4x Netty nodes10x Kafka, DNS, the usual suspects…

Page 159: Netty from the trenches

I KNOW IT’S NOT FAIR,

but it’s good stuff for your ego BRO

Page 160: Netty from the trenches

Lovely ecosystemlike Ratpack,

or users, with vert.x or akka

Page 161: Netty from the trenches

It will change the way you program some of your apps

Page 162: Netty from the trenches

Hello, Async problems

Page 163: Netty from the trenches

Forget about max onn params

Page 164: Netty from the trenches

One more thing...

Page 165: Netty from the trenches

(It’s 5:00 in the morning and I had

to say it)

Page 166: Netty from the trenches

(did you notice the “Apple

background”?)

Page 167: Netty from the trenches
Page 168: Netty from the trenches
Page 169: Netty from the trenches

JUST KIDDINGIt doesn’ really

matter!

Page 170: Netty from the trenches

Have fun!

Page 171: Netty from the trenches

THANKS

Page 172: Netty from the trenches

ProTip: We’re hiring

Page 173: Netty from the trenches

Q & A

#HiddenTrovitTrack@jordi9