SlideShare a Scribd company logo
Introduction to Akka HTTP
Building scalable rest service in Scala
https://github.com/shashankgowdal/introduction-to-akkahttp
● Shashank L
● Senior Software engineer at Tellius
● Part time big data consultant and trainer
at datamantra.io
● www.shashankgowda.com
Agenda
● Motivation
● Akka, Reactive streams
● Akka Http
● Akka Http High level API
● Testing
● Additional functionality
● Working with files
● Websockets
● Akka Http with Spark
Scala frameworks to build REST API
● Play/Lift
○ Full stack web framework
● Scalatra
○ Lightweight but requires a application container for
deployment
● Spray
○ Lightweight and robust as it's asynchronous and built on top
of Actors
● Akka HTTP
○ Next version of Spray framework

Recommended for you

Introduction to Spark Streaming
Introduction to Spark StreamingIntroduction to Spark Streaming
Introduction to Spark Streaming

It Provide a way to consume continues stream of data. Build on top of Spark Core It supports Java, Scala and Python. API is similar to Spark Core.

knowledge sharingapache sparkspark
Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0

Spark 2.0 is a major release of Apache Spark. This release has brought many changes to API(s) and libraries of Spark. So in this KnolX, we will be looking at some improvements that are made in Spark 2.0. Also, in these slides we will be getting an introduction to some new features in Spark 2,0 like SparkSession API and Structured Streaming.

apache spark 2sparkapache
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...

Things were easier when all our data used to be offline, analyzed overnight in batches. Now our data is online, in motion, and generated constantly. For architects, developers and their businesses, this means that there is an urgent need for tools and applications that can deliver real-time (or near real-time) streaming ETL capabilities. In this session by Konrad Malawski, author, speaker and Senior Akka Engineer at Lightbend, you will learn how to build these streaming ETL pipelines with Akka Streams, Alpakka and Apache Kafka, and why they matter to enterprises that are increasingly turning to streaming Fast Data applications.

akkaakka streamsalpakka
Why Akka HTTP
● Its 2.0 version of Spray.io
● Internals of Spray have been rewritten to use
Reactive streams
● Reactive streams idea gel well with earlier ideas of
Spray
● Multiple level API
Akka
● Toolkit and runtime for building highly concurrent,
distributed, and fault tolerant applications on the JVM
● Uses message passing based concurrency model
● Written in Scala
● Scale up or out
● Program at higher level
● Distributable by design
● Message passing is built on top of AkkaActor model
Akka actor
● Receives message and takes action to handle them
● Consists of
○ Behaviour
○ State
○ Mailbox
Reactive streams
● Asynchronous
● Stream processing
● Back-pressured
● Interoperability
● Few Implementations
○ Akka Streams
○ RxJava
○ Play
○ Kafka
● Spark streaming with Kafka receiver

Recommended for you

Structured Streaming with Kafka
Structured Streaming with KafkaStructured Streaming with Kafka
Structured Streaming with Kafka

This document provides an overview of structured streaming with Kafka in Spark. It discusses data collection vs ingestion and why they are key. It also covers Kafka architecture and terminology. It describes how Spark integrates with Kafka for streaming data sources. It explains checkpointing in structured streaming and using Kafka as a sink. The document discusses delivery semantics and how Spark supports exactly-once semantics with certain output stores. Finally, it outlines new features in Kafka for exactly-once guarantees and the future of structured streaming.

apache sparkbangalore apache spark meetupspark streaming
Introduction to Datasource V2 API
Introduction to Datasource V2 APIIntroduction to Datasource V2 API
Introduction to Datasource V2 API

A brief introduction to Datasource V2 API in Spark 2.3.0, Comparison with the previous Datasource API.

apache sparkbangalore apache spark meetupdatasource
Serverless Event Streaming with Pulsar Functions
Serverless Event Streaming with Pulsar FunctionsServerless Event Streaming with Pulsar Functions
Serverless Event Streaming with Pulsar Functions

The last few years have seen the emergence of Serverless as a paradigm for event streaming. Its very simple programming model has attracted developers in droves. At the same time, its ability to elastically scale has simplified operations significantly. Combined together with the ubiquity of their presence across all cloud providers, serverless today has become the leading choice to do event processing at scale for a lot of companies. In this talk, Sijie Guo from StreamNative will explore how the serverless paradigm is applied to event streaming in Apache Pulsar, a next-generation event streaming system. Pulsar provides native support for serverless functions where the events are processed as soon as they arrive in a streaming manner and that provides flexible deployment options (thread, process, container). He will describe how these serverless functions make data engineering easier and share the real world usage of Pulsar Functions.

serverlessevent streamingpubsub
Akka streams
● Akka’s implementation of Reactive streams
● DSL for building a complete stream
● Higher level abstraction over the actor model
● Stream inputs and outputs are typesafe
● Internally uses Actor to implement Reactive stream
properties
Source, Flow and Sink
Source, Flow and Sink
com.shashank.akkahttp.IntroductionToStream
implicit val sys = ActorSystem("IntroductionToStream")
implicit val mat:Materializer = ActorMaterializer()
val source = Source(List(1, 2, 3))
val flow = Flow[Int].map(_.toString)
val sink = Sink.foreach(println)
val runnableGraph = source via flow to sink
runnableGraph.run()
HTTP server with Akka streams
HTTPServer as a:
Flow[HttpRequest, HttpResponse]
Socket
input
Bytes ⇒
HttpRequest
HttpRequest ⇒
HttpResponse
HttpResponse
⇒ Bytes
Socket
Sink

Recommended for you

Migrating to spark 2.0
Migrating to spark 2.0Migrating to spark 2.0
Migrating to spark 2.0

Spark 2.0 introduces several major changes including using Dataset as the main abstraction, replacing RDDs for optimized performance. The migration involves updating to Scala 2.11, replacing contexts with SparkSession, using built-in CSV connector, updating RDD-based code to use Dataset APIs, adding checks for cross joins, and updating custom ML transformers. Migrating leverages many of the improvements in Spark 2.0 while addressing breaking changes.

bangalore apache spark meetuplatest sparkspark2.0
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures

The term 'streams' has been getting pretty overloaded recently–it's hard to know where to best use different technologies with streams in the name. In this talk by noted hAkker Konrad Malawski, we'll disambiguate what streams are and what they aren't, taking a deeper look into Akka Streams (the implementation) and Reactive Streams (the standard). You'll be introduced to a number of real life scenarios where applying back-pressure helps to keep your systems fast and healthy at the same time. While the focus is mainly on the Akka Streams implementation, the general principles apply to any kind of asynchronous, message-driven architectures.

akka streamsactor systemkafka
Akka streams
Akka streamsAkka streams
Akka streams

Akka Streams is an implementation of Reactive Streams, which is a standard for asynchronous stream processing with non-blocking backpressure on the JVM. In this talk we'll cover the rationale behind Reactive Streams, and explore the different building blocks available in Akka Streams. I'll use Scala for all coding examples, but Akka Streams also provides a full-fledged Java8 API.After this session you will be all set and ready to reap the benefits of using Akka Streams!

javajava8akka
Akka Http server using Flow
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
val requestResponseFlow = Flow.fromFunction[HttpRequest, HttpResponse]( request => {
println(request.toString)
HttpResponse(StatusCodes.OK, entity = "Hello!")
})
Http().bindAndHandle(requestResponseFlow, "localhost", 8080)
com.shashank.akkahttp.basic.serving.StreamsServing
Akka HTTP
● Part of Akka project
● HTTP toolkit (Client and Server)
● On top of akka-actor and akka-streams
● Multiple levels of abstraction - Open API
● Scalable, Max throughput, acceptable latency
● APIs in both Scala and Java
Akka HTTP - Implementation
● Fully asynchronous and nonblocking
● Focused on higher level API
● Lightweight
● Modular
● Testable
● Based on spray.io
● Better streaming REST functionality support
Akka HTTP stack

Recommended for you

Spark on Kubernetes
Spark on KubernetesSpark on Kubernetes
Spark on Kubernetes

Spark can run on Kubernetes containers in two ways - as a static cluster or with native integration. As a static cluster, Spark pods are manually deployed without autoscaling. Native integration treats Kubernetes as a resource manager, allowing Spark to dynamically acquire and release containers like in YARN. It uses Kubernetes custom controllers to create driver pods that then launch worker pods. This provides autoscaling of resources based on job demands.

apache sparkkubernetesbangalore apache spark meetup
Introduction to Structured streaming
Introduction to Structured streamingIntroduction to Structured streaming
Introduction to Structured streaming

This document provides an introduction to Structured Streaming in Apache Spark. It discusses the evolution of stream processing, drawbacks of the DStream API, and advantages of Structured Streaming. Key points include: Structured Streaming models streams as infinite tables/datasets, allowing stream transformations to be expressed using SQL and Dataset APIs; it supports features like event time processing, state management, and checkpointing for fault tolerance; and it allows stream processing to be combined more easily with batch processing using the common Dataset abstraction. The document also provides examples of reading from and writing to different streaming sources and sinks using Structured Streaming.

apache sparkbangalore apache spark meetupspark streaming
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3

The document discusses Reactive Slick, a new version of the Slick database access library for Scala that provides reactive capabilities. It allows parallel database execution and streaming of large query results using Reactive Streams. Reactive Slick is suitable for composite database tasks, combining async tasks, and processing large datasets through reactive streams.

slickscalareactive
Akka HTTP structure
Akka HTTP module
akka-http
akka-http-core
akka-http-testkit
akka-http-
spray-json
akka-http-xml
Akka HTTP - Parts
● akka-http-core
○ low-level server & client side HTTP implementation
● akka-http
○ high-level API : DSL, (un)marshalling, (de)compression
● akka-http-testkit
○ Utilities for testing server-side implementation
● akka-http-spray-json
○ (de)serialization from/to JSON with spray-json
● akka-http-xml
○ (de)serialization from/to XML with scala-xml
HTTP model
● Fully immutable, case-class based
● Abstraction for most HTTP things (Types!)
● Little logic inside
● Lots of predefined types - media type, status code,
encodings etc
● Efficient parsing and rendering
● Clients/Connected services should obey the standard
HTTP model - Examples
case class HttpRequest(method: HttpMethod = HttpMethods.GET,
uri: Uri = Uri./,
headers: immutable.Seq[HttpHeader] = Nil,
entity: RequestEntity = HttpEntity.Empty,
protocol: HttpProtocol = HttpProtocols.`HTTP/1.1`)
case class HttpResponse(status: StatusCode = StatusCodes.OK,
headers: immutable.Seq[HttpHeader] = Nil,
entity: ResponseEntity = HttpEntity.Empty,
protocol: HttpProtocol = HttpProtocols.`HTTP/1.1`)
case class Uri(scheme: String,
authority: Authority,
path: Path,
rawQueryString: Option[String],
fragment: Option[String])

Recommended for you

Specs2 whirlwind tour at Scaladays 2014
Specs2 whirlwind tour at Scaladays 2014Specs2 whirlwind tour at Scaladays 2014
Specs2 whirlwind tour at Scaladays 2014

Presentation of specs2 functionalities from simple ones to less well-known + overview of the next release

specs2
Building real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark StreamingBuilding real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark Streaming

This document summarizes the key challenges and solutions in building a real-time data pipeline that ingests data from a database, transforms it using Spark Streaming, and publishes the output to Salesforce. The pipeline aims to have a latency of 1 minute with zero data loss and ordering guarantees. Some challenges discussed include handling out of sequence and late arrival events, schema evolution, bootstrap loading, data loss/corruption, and diagnosing issues. Solutions proposed use Kafka, checkpointing, replay capabilities, and careful broker/connect setups to help meet the reliability requirements for the pipeline.

apache sparkbangalore apache spark meetupspark meetup
Designing Payloads for Event-Driven Systems | Lorna Mitchell, Aiven
Designing Payloads for Event-Driven Systems | Lorna Mitchell, AivenDesigning Payloads for Event-Driven Systems | Lorna Mitchell, Aiven
Designing Payloads for Event-Driven Systems | Lorna Mitchell, Aiven

Event-driven systems come in different shapes and sizes, and the rules for payload construction are: there are no rules (but there are guidelines). Flexible payloads are both the best and worst thing about event streaming - you never quite know what to expect from each system's payloads. Just like when you met your first NoSQL datastore, this sounds like chaos! In this session we will cover strategies for designing the payloads you stream over Kafka. From fields to include, common mistakes to avoid, and what to do when the data structure changes over time, this session has real-world advice and examples that you can apply in your own projects. We will also look at other aspects, such as when to use a self-contained data format such as JSON or XML, or when a serialization format like Avro is best - and how to handle the schemas. This session is recommended for anyone who wants to design their payloads right first time and have all their applications playing nicely together.

kafka summitapache kafkapayloads
HTTP model - Examples
object ContentTypes {
val `application/json` = ContentType(MediaTypes.`application/json`)
val `application/octet-stream` = ContentType(MediaTypes.`application/octet-stream`)
val `text/plain(UTF-8)` = MediaTypes.`text/plain` withCharset HttpCharsets.`UTF-8`
val `text/html(UTF-8)` = MediaTypes.`text/html` withCharset HttpCharsets.`UTF-8`
val `text/xml(UTF-8)` = MediaTypes.`text/xml` withCharset HttpCharsets.`UTF-8`
val `text/csv(UTF-8)` = MediaTypes.`text/csv` withCharset HttpCharsets.`UTF-8`
val NoContentType = ContentType(MediaTypes.NoMediaType)
}
val `US-ASCII` = register("US-ASCII")("iso-ir-6", "ANSI_X3.4-1968", "ANSI_X3.4-1986", "ISO_646.irv:1991", "ASCII", "ISO646-US",
"us", "IBM367", "cp367", "csASCII")
val `ISO-8859-1` = register("ISO-8859-1")("iso-ir-100", "ISO_8859-1", "latin1", "l1", "IBM819", "CP819", "csISOLatin1")
val `UTF-8` = register("UTF-8")("UTF8")
val `UTF-16` = register("UTF-16")("UTF16")
val `UTF-16BE` = register("UTF-16BE")()
val `UTF-16LE` = register("UTF-16LE")()
HTTP server functional way
● Low level HTTP API
● Provided by akka-http-core-module
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
val handler :(HttpRequest => HttpResponse) = {
case HttpRequest(HttpMethods.GET, Uri.Path("/ping"), _, _, _) =>
HttpResponse(StatusCodes.OK, entity = "pong!")
case r =>
HttpResponse(status = StatusCodes.BadRequest)
}
Http().bindAndHandleSync(handler, "localhost", 8080)
com.shashank.akkahttp.basic.serving.FunctionalServing
Akka Http high level API
HTTP Server Nice way!
● Low level API becomes uneasy to handle when we
need large number of routes
● For this we should use higher level API by akka-http
● Route using Routing DSL
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
val routes: Route = ???
Http(sys).bindAndHandle(route, "localhost", 8090)

Recommended for you

Revitalizing Enterprise Integration with Reactive Streams
Revitalizing Enterprise Integration with Reactive StreamsRevitalizing Enterprise Integration with Reactive Streams
Revitalizing Enterprise Integration with Reactive Streams

With Viktor Klang, Deputy CTO Lightbend, Inc. As software grows more and more interconnected, and with several generations of software having to interoperate, a new take on the integration of systems is needed—ad hoc, unversioned, and unreplicated scripts just won’t suffice, and the traditional Enterprise Service Bus (ESB) concept has experienced stability, reliability, performance, and scalability problems. In this webinar, Viktor explores a new take on Enterprise Integration Patterns: First, he will explore the Reactive Streams standard, an orchestration layer where transformations are standalone, composable, reusable, and—most importantly—using asynchronous flow-control—back pressure—to maintain predictable, stable, behavior over time. Furthermore, he will go through how one-off workloads relate to continuous, and batch, workloads, and how they can be addressed by that very same orchestration layer. Finally, he will review how this type of design achieves resilience, scalability, and ultimately—responsiveness.

webinarlightbendintegration
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...

Akka Streams and its amazing handling of stream back-pressure should be no surprise to anyone. But it takes a couple of use cases to really see it in action - especially use cases where the amount of work increases as you process make you really value the back-pressure. This talk takes a sample web crawler use case where each processing pass expands to a larger and larger workload to process, and discusses how we use the buffering capabilities in Kafka and the back-pressure with asynchronous processing in Akka Streams to handle such bursts. In addition, we will also provide some constructive “rants” about the architectural components, the maturity, or immaturity you’ll expect, and tidbits and open source goodies like memory-mapped stream buffers that can be helpful in other Akka Streams and/or Kafka use cases.

reactivesummit16
Telco analytics at scale
Telco analytics at scaleTelco analytics at scale
Telco analytics at scale

This document discusses Telco analytics at scale using distributed stream processing. It describes using technologies like Apache Spark Streaming, Kafka, and Hadoop (HDFS, Hive, HBase) to ingest and process large volumes of streaming data from various sources in real-time or near real-time. Example use cases discussed include fraud detection, real-time rating, security information and event management. It also covers strategies for distributed in-memory caching and rule processing to enable low latency analytics at high throughput scales needed for telco data and applications.

télécommunicationsanalyticssubex
Routing DSL
● Internal domain specific language for routing
● How most services are actually written
● Layer to the application
● Type safe but flexible
● Not just routing - behaviour definition
● Very composable
● Fun, powerful and looks clean
Routing DSL - Example
val route =
path("welcome"){
get{
complete {
"welcome to rest service"
}
}
} ~
path("demo"){
get{
complete {
"welcome to demonstration"
}
}
}
Http().bindAndHandle(route, "localhost", 8090)
com.shashank.akkahttp.basic.routing.RoutingDSL
Directives
● A Directive is a small building block used for creating
routes.
● There are some predefined directives( get, post,
complete etc.)
● We can also define our custom directives.
● Roles: extracting, transforming request or response,
filtering, side-effecting
● ~136 predefined directives
Rejections
● Produced by directives
● Travel down the routing structure
● EmptyRejection is thrown when no route completes
● Can be extended
● Can be cancelled
● Handling rejection = transforming it to response
● Ex. MethodRejection, AuthorizationFailedRejection,
MissingCookieRejection, MissingQueryParamRejection

Recommended for you

Building a Reactive RESTful API with Akka Http & Slick
Building a Reactive RESTful API with Akka Http & SlickBuilding a Reactive RESTful API with Akka Http & Slick
Building a Reactive RESTful API with Akka Http & Slick

Dan Persa, Senior Software Engineer at Zalando Dan Persa has been a software engineer at Zalando since 2013 and is a member of the Fashion Store team, which is responsible for Zalando’s core ecommerce business. He loves Java and Scala and more recently has been exploring Go and Node.js. He’s a big fan of Clean Code and Software Craftsmanship. In addition to coding, he enjoys mentoring new developers, organizing coder dojos and reading groups and giving tech talks. In his free time he likes to take photos and dance salsa. tech.zalando.com

microserviceszalandoapis
An Introduction to Akka http
An Introduction to Akka httpAn Introduction to Akka http
An Introduction to Akka http

An introduction to akka-http and its components, why akka http over spray? and high level server API and its components.

knolxknoldusakka
Platform for Data Scientists
Platform for Data ScientistsPlatform for Data Scientists
Platform for Data Scientists

This document discusses a platform for data scientists that aims to automate routine jobs, maximize resource utilization, and allow data scientists to focus more on business solutions. The platform provides capabilities for data capture, analysis, modeling, and output of analytics. It seeks to reduce the time taken to turn data into insights from months to weeks. Key elements of the platform include tools for exploratory data analysis, advanced modeling, distributed architecture, bespoke algorithms, and packaged analytics solutions.

datascientssubexanalytics
Rejections
● ~ operator connects two routes in a way that allows a
second route to get a go at a request if the first route
"rejected" it.
path("order") {
get {
complete("Received GET")
} ~
post {
complete("Received POST")
}
}
com.shashank.akkahttp.basic.routing.Rejection
Failures
● Are triggered by exceptions
● Travel up the routing structure
● Can be handled by handleExceptions directive or
top-level ExceptionHandler
● Can be used to simplify the flow for validation
purpose
com.shashank.akkahttp.basic.routing.Failure
Testing Akka Http
● Simple and straightforward
● Allows to assert responses returned for given
requests
● Integrates well with Scalatest
Get("/ping") ~> route ~> check{
status === OK
entity.as[String] === "It Works!"
}
com.shashank.akkahttp.basic.routing.TestKit
Testkit

Recommended for you

Akka http 2
Akka http 2Akka http 2
Akka http 2

This document provides an overview and introduction to Akka HTTP, a Scala library built on Akka Streams for HTTP-based applications. Some key points: - Akka HTTP uses Akka Streams to model HTTP requests and responses as streaming data flows. - It allows building both HTTP clients and servers by composing stream processing stages together. - Common directives and operations like routing, marshalling, validation, and testing are supported through a high-level API. - Examples demonstrate basic usage like creating a route that returns XML, running a server, and writing tests against routes.

javahttpscala
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP

Going down the microservices route makes a lot of things around creating and maintaining large systems easier but it comes at a cost too, particularly associated with challenges around security. While securing monolithic applications was a relatively well understood area, the same can't be said about microservice based architectures. This presentation covers how implementing microservices affects the security of distributed systems, outlines pros and cons of several standards and common practices and offers practical suggestions for securing microservice based systems using Play and Akka HTTP.

apiakka httpakka
Interactive Data Analysis in Spark Streaming
Interactive Data Analysis in Spark StreamingInteractive Data Analysis in Spark Streaming
Interactive Data Analysis in Spark Streaming

This document discusses strategies for building interactive streaming applications in Spark Streaming. It describes using Zookeeper as a dynamic configuration source to allow modifying a Spark Streaming application's behavior at runtime. The key points are: - Zookeeper can be used to track configuration changes and trigger Spark Streaming context restarts through its watch mechanism and Curator library. - This allows building interactive applications that can adapt to configuration updates without needing to restart the whole streaming job. - Examples are provided of using Curator caches like node and path caches to monitor Zookeeper for changes and restart Spark Streaming contexts in response.

bangalore apache spark meetupapache sparkspark streaming
Additional Rest functionalities in
Akka Http
Query parameters
def parameters(param: <ParamDef[T]>): Directive1[T]
● Mandatory parameters
● Optional parameters
● Parameters with required value
● Deserialized parameter
● Repeated parameter
● Deserialized parameter into Case class
(Un)Marshalling
● Marshalling - high level → low (wire) level
● Unmarshalling - low (wire) level → high level
● Many predefined (un) marshallers are available
● Extensible
● JSON and XML supported
● Type-class approach - Implicit resolution
Custom Http entity data
● Akka Http JSON support
● Support conversion to and from JVM objects to wire
representation like JSON, XML etc
● SprayJsonSupport provides a
FromEntityUnmarshaller[T] and ToEntityMarshaller[T]
for every type T with Spray Json Reader/Writer
com.shashank.akkahttp.basic.routing.CustomEntityWithJson

Recommended for you

Akka-http
Akka-httpAkka-http
Akka-http

This document discusses the development of a single-page web application for a student markbook using Akka actors and HTTP. Key points discussed include: - Using multiple Akka actors to retrieve student, schedule, subject and mark data from various data services. - A worker actor that processes the retrieved data and returns student week marks. - A REST API with routes to get lists of students and individual student week marks. - The application server is initialized by binding the API routes to an HTTP server.

exactprokostromaakka
Akka HTTP
Akka HTTPAkka HTTP
Akka HTTP

2016/3/4 @Akkaを語る会

akkascala
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015

Everyone in the Scala world is using or looking into using Akka for low-latency, scalable, distributed or concurrent systems. I'd like to share my story of developing and productionizing multiple Akka apps, including low-latency ingestion and real-time processing systems, and Spark-based applications. When does one use actors vs futures? Can we use Akka with, or in place of, Storm? How did we set up instrumentation and monitoring in production? How does one use VisualVM to debug Akka apps in production? What happens if the mailbox gets full? What is our Akka stack like? I will share best practices for building Akka and Scala apps, pitfalls and things we'd like to avoid, and a vision of where we would like to go for ideal Akka monitoring, instrumentation, and debugging facilities. Plus backpressure and at-least-once processing.

akkamonitoringscala
Custom directive
● Configuration labelling
● Transforming existing directives
● Directive0, Directive1
● Authorization
● Authentication
com.shashank.akkahttp.basic.routing.CustomDirective
Working with Files
File upload
def uploadedFile(fieldName: String): Directive1[(FileInfo, File)]
● Streams the contents of a file uploaded as a multipart
form into a temporary file on disk
● Cannot start processing the file unless it written
completely to temporary file
com.shashank.akkahttp.basic.routing.FileUpload
File upload stream
def fileUpload(fieldName: String): Directive1[(FileInfo,
Source[ByteString, Any])]
● Simple access to the stream of bytes for a file
uploaded as a multipart form together with metadata
about the upload as extracted value.
com.shashank.akkahttp.basic.routing.FileUploadStream

Recommended for you

Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala

This document provides an overview of functional programming concepts in Scala. It discusses the history and advantages of functional programming. It then covers the basics of Scala including its support for object oriented and functional programming. Key functional programming aspects of Scala like immutable data, higher order functions, and implicit parameters are explained with examples.

bangalore apache spark meetupfunctional programmingapache spark
The Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOneThe Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOne

The document discusses Akka, a toolkit for building highly concurrent, distributed, and resilient message-driven applications on the JVM. It describes key components of Akka including actors for concurrency, clusters for location-transparent resilient applications, persistence for event sourcing, and HTTP for asynchronous reactive servers. It also discusses the actor model of concurrent computation and related topics like reactive streams and advantages of asynchronous messaging.

akkareactiverestless
Akka http
Akka httpAkka http
Akka http

This document provides an overview of Akka HTTP, a library for building HTTP-based services using Scala and Akka. It describes the common abstractions used in Akka HTTP like HTTP requests, responses, entities, and marshalling/unmarshalling. It also explains the low-level and high-level APIs, with the low-level API providing basic request handling functionality and the high-level API using directives and routing DSL for defining routes in a more flexible way.

knowledge sharingknolxakka http
Websockets
Websocket
● WebSocket is a protocol that provides a bi-directional channel
between browser and webserver
● Data is exchanged in messages whereby a message can either
be binary data or unicode text
Server side websocket in AkkaHttp
● Akka HTTP provides a stream-based implementation of the
WebSocket protocol
● basic unit of data exchange in the WebSocket is a message i.e
TextMessage or BinaryMessage
● Websocket handshake is managed and hidden from application
layer
● A message handler is expected to be implemented as a
Flow[Message, Message, Any]
● Testing Websocket using WSProbe
com.shashank.akkahttp.basic.routing.Websocket
Akka HTTP with Spark
Spark Cluster
Akka Http
Rest
server
Client
HDFS

Recommended for you

Real time ETL processing using Spark streaming
Real time ETL processing using Spark streamingReal time ETL processing using Spark streaming
Real time ETL processing using Spark streaming

The document discusses the architecture for real-time ETL processing, including using GoldenGate for change data capture from source databases, Kafka as the messaging system, and Spark jobs for streaming reconciliation and joining of data. It also covers requirements for the reconciler component like supporting idempotency, immutability, and schema evolution. Challenges with handling out-of-order events in Spark streaming and the data model used to address issues like idempotency and schema evolution are also described.

intuitapache sparkbangalore apache spark meetup
Productionalizing a spark application
Productionalizing a spark applicationProductionalizing a spark application
Productionalizing a spark application

1. The document discusses the process of productionalizing a financial analytics application built on Spark over multiple iterations. It started with data scientists using Python and data engineers porting code to Scala RDDs. They then moved to using DataFrames and deployed on EMR. 2. Issues with code quality and testing led to adding ScalaTest, PR reviews, and daily Jenkins builds. Architectural challenges were addressed by moving to Databricks Cloud which provided notebooks, jobs, and throwaway clusters. 3. Future work includes using Spark SQL windows and Dataset API for stronger typing and schema support. The iterations improved the code, testing, deployment, and use of latest Spark features.

spark meetupbangalore apache spark meetupapache spark
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst

This document provides an overview of Spark Catalyst including: - Catalyst trees and expressions represent logical and physical query plans - Expressions have datatypes and operate on Row objects - Custom expressions can be defined - Code generation improves expression evaluation performance by generating Java code via Janino compiler - Key concepts like trees, expressions, datatypes, rows, code generation and Janino compiler are explained through examples

catalystspark sql optimizerapache spark
Pros and Cons
● Pros
○ Backed by Lightbend(Typesafe)
○ Integration layers
○ Microservices
○ Pure REST APIs
● Cons
○ Full fledged web applications (server side template generation)
○ Not mature enough
○ Easy to start, hard to master
References
● Akka HTTP - A reactive web toolkit
● Akka HTTP - What, Why and How
● Introduction to Akka HTTP
● Akka HTTP documentation
http://doc.akka.io/docs/akka/2.4.2/scala/http/
● http://blog.madhukaraphatak.com/categories/akka-http/

More Related Content

What's hot

Building distributed processing system from scratch - Part 2
Building distributed processing system from scratch - Part 2Building distributed processing system from scratch - Part 2
Building distributed processing system from scratch - Part 2
datamantra
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
Kevin Webber
 
Building Distributed Systems from Scratch - Part 1
Building Distributed Systems from Scratch - Part 1Building Distributed Systems from Scratch - Part 1
Building Distributed Systems from Scratch - Part 1
datamantra
 
Introduction to Spark Streaming
Introduction to Spark StreamingIntroduction to Spark Streaming
Introduction to Spark Streaming
Knoldus Inc.
 
Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0
Knoldus Inc.
 
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Lightbend
 
Structured Streaming with Kafka
Structured Streaming with KafkaStructured Streaming with Kafka
Structured Streaming with Kafka
datamantra
 
Introduction to Datasource V2 API
Introduction to Datasource V2 APIIntroduction to Datasource V2 API
Introduction to Datasource V2 API
datamantra
 
Serverless Event Streaming with Pulsar Functions
Serverless Event Streaming with Pulsar FunctionsServerless Event Streaming with Pulsar Functions
Serverless Event Streaming with Pulsar Functions
StreamNative
 
Migrating to spark 2.0
Migrating to spark 2.0Migrating to spark 2.0
Migrating to spark 2.0
datamantra
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Lightbend
 
Akka streams
Akka streamsAkka streams
Akka streams
mircodotta
 
Spark on Kubernetes
Spark on KubernetesSpark on Kubernetes
Spark on Kubernetes
datamantra
 
Introduction to Structured streaming
Introduction to Structured streamingIntroduction to Structured streaming
Introduction to Structured streaming
datamantra
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
takezoe
 
Specs2 whirlwind tour at Scaladays 2014
Specs2 whirlwind tour at Scaladays 2014Specs2 whirlwind tour at Scaladays 2014
Specs2 whirlwind tour at Scaladays 2014
Eric Torreborre
 
Building real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark StreamingBuilding real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark Streaming
datamantra
 
Designing Payloads for Event-Driven Systems | Lorna Mitchell, Aiven
Designing Payloads for Event-Driven Systems | Lorna Mitchell, AivenDesigning Payloads for Event-Driven Systems | Lorna Mitchell, Aiven
Designing Payloads for Event-Driven Systems | Lorna Mitchell, Aiven
HostedbyConfluent
 
Revitalizing Enterprise Integration with Reactive Streams
Revitalizing Enterprise Integration with Reactive StreamsRevitalizing Enterprise Integration with Reactive Streams
Revitalizing Enterprise Integration with Reactive Streams
Lightbend
 
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...
Reactivesummit
 

What's hot (20)

Building distributed processing system from scratch - Part 2
Building distributed processing system from scratch - Part 2Building distributed processing system from scratch - Part 2
Building distributed processing system from scratch - Part 2
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
 
Building Distributed Systems from Scratch - Part 1
Building Distributed Systems from Scratch - Part 1Building Distributed Systems from Scratch - Part 1
Building Distributed Systems from Scratch - Part 1
 
Introduction to Spark Streaming
Introduction to Spark StreamingIntroduction to Spark Streaming
Introduction to Spark Streaming
 
Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0Introduction to Apache Spark 2.0
Introduction to Apache Spark 2.0
 
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
 
Structured Streaming with Kafka
Structured Streaming with KafkaStructured Streaming with Kafka
Structured Streaming with Kafka
 
Introduction to Datasource V2 API
Introduction to Datasource V2 APIIntroduction to Datasource V2 API
Introduction to Datasource V2 API
 
Serverless Event Streaming with Pulsar Functions
Serverless Event Streaming with Pulsar FunctionsServerless Event Streaming with Pulsar Functions
Serverless Event Streaming with Pulsar Functions
 
Migrating to spark 2.0
Migrating to spark 2.0Migrating to spark 2.0
Migrating to spark 2.0
 
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous ArchitecturesUnderstanding Akka Streams, Back Pressure, and Asynchronous Architectures
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Spark on Kubernetes
Spark on KubernetesSpark on Kubernetes
Spark on Kubernetes
 
Introduction to Structured streaming
Introduction to Structured streamingIntroduction to Structured streaming
Introduction to Structured streaming
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
 
Specs2 whirlwind tour at Scaladays 2014
Specs2 whirlwind tour at Scaladays 2014Specs2 whirlwind tour at Scaladays 2014
Specs2 whirlwind tour at Scaladays 2014
 
Building real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark StreamingBuilding real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark Streaming
 
Designing Payloads for Event-Driven Systems | Lorna Mitchell, Aiven
Designing Payloads for Event-Driven Systems | Lorna Mitchell, AivenDesigning Payloads for Event-Driven Systems | Lorna Mitchell, Aiven
Designing Payloads for Event-Driven Systems | Lorna Mitchell, Aiven
 
Revitalizing Enterprise Integration with Reactive Streams
Revitalizing Enterprise Integration with Reactive StreamsRevitalizing Enterprise Integration with Reactive Streams
Revitalizing Enterprise Integration with Reactive Streams
 
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Ka...
 

Viewers also liked

Telco analytics at scale
Telco analytics at scaleTelco analytics at scale
Telco analytics at scale
datamantra
 
Building a Reactive RESTful API with Akka Http & Slick
Building a Reactive RESTful API with Akka Http & SlickBuilding a Reactive RESTful API with Akka Http & Slick
Building a Reactive RESTful API with Akka Http & Slick
Zalando Technology
 
An Introduction to Akka http
An Introduction to Akka httpAn Introduction to Akka http
An Introduction to Akka http
Knoldus Inc.
 
Platform for Data Scientists
Platform for Data ScientistsPlatform for Data Scientists
Platform for Data Scientists
datamantra
 
Akka http 2
Akka http 2Akka http 2
Akka http 2
Jean Detoeuf
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
Rafal Gancarz
 
Interactive Data Analysis in Spark Streaming
Interactive Data Analysis in Spark StreamingInteractive Data Analysis in Spark Streaming
Interactive Data Analysis in Spark Streaming
datamantra
 
Akka-http
Akka-httpAkka-http
Akka-http
Iosif Itkin
 
Akka HTTP
Akka HTTPAkka HTTP
Akka HTTP
TanUkkii
 
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015
Evan Chan
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
datamantra
 
The Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOneThe Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOne
Konrad Malawski
 
Akka http
Akka httpAkka http
Akka http
Knoldus Inc.
 
Real time ETL processing using Spark streaming
Real time ETL processing using Spark streamingReal time ETL processing using Spark streaming
Real time ETL processing using Spark streaming
datamantra
 
Productionalizing a spark application
Productionalizing a spark applicationProductionalizing a spark application
Productionalizing a spark application
datamantra
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst
datamantra
 
Akka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based ApplicationsAkka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based Applications
NLJUG
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
Discovery
DiscoveryDiscovery
Discovery
Pat Ferrel
 
Microservices - it's déjà vu all over again
Microservices  - it's déjà vu all over againMicroservices  - it's déjà vu all over again
Microservices - it's déjà vu all over again
Arnon Rotem-Gal-Oz
 

Viewers also liked (20)

Telco analytics at scale
Telco analytics at scaleTelco analytics at scale
Telco analytics at scale
 
Building a Reactive RESTful API with Akka Http & Slick
Building a Reactive RESTful API with Akka Http & SlickBuilding a Reactive RESTful API with Akka Http & Slick
Building a Reactive RESTful API with Akka Http & Slick
 
An Introduction to Akka http
An Introduction to Akka httpAn Introduction to Akka http
An Introduction to Akka http
 
Platform for Data Scientists
Platform for Data ScientistsPlatform for Data Scientists
Platform for Data Scientists
 
Akka http 2
Akka http 2Akka http 2
Akka http 2
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
 
Interactive Data Analysis in Spark Streaming
Interactive Data Analysis in Spark StreamingInteractive Data Analysis in Spark Streaming
Interactive Data Analysis in Spark Streaming
 
Akka-http
Akka-httpAkka-http
Akka-http
 
Akka HTTP
Akka HTTPAkka HTTP
Akka HTTP
 
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
The Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOneThe Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOne
 
Akka http
Akka httpAkka http
Akka http
 
Real time ETL processing using Spark streaming
Real time ETL processing using Spark streamingReal time ETL processing using Spark streaming
Real time ETL processing using Spark streaming
 
Productionalizing a spark application
Productionalizing a spark applicationProductionalizing a spark application
Productionalizing a spark application
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst
 
Akka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based ApplicationsAkka in Practice: Designing Actor-based Applications
Akka in Practice: Designing Actor-based Applications
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
 
Discovery
DiscoveryDiscovery
Discovery
 
Microservices - it's déjà vu all over again
Microservices  - it's déjà vu all over againMicroservices  - it's déjà vu all over again
Microservices - it's déjà vu all over again
 

Similar to Building scalable rest service using Akka HTTP

Scala45 spray test
Scala45 spray testScala45 spray test
Scala45 spray test
kopiczko
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
Geoff Ballinger
 
Exploring Reactive Integrations With Akka Streams, Alpakka And Apache Kafka
Exploring Reactive Integrations With Akka Streams, Alpakka And Apache KafkaExploring Reactive Integrations With Akka Streams, Alpakka And Apache Kafka
Exploring Reactive Integrations With Akka Streams, Alpakka And Apache Kafka
Lightbend
 
Building REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with ScalaBuilding REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with Scala
Knoldus Inc.
 
Akka streams - Umeå java usergroup
Akka streams - Umeå java usergroupAkka streams - Umeå java usergroup
Akka streams - Umeå java usergroup
Johan Andrén
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
Paweł Kowalczuk
 
2 Asp Dot Net Ajax Extensions
2 Asp Dot Net Ajax Extensions2 Asp Dot Net Ajax Extensions
2 Asp Dot Net Ajax Extensions
Abhishek Bhatnagar
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
Johan Andrén
 
RESTful SCA with Apache Tuscany
RESTful SCA with Apache TuscanyRESTful SCA with Apache Tuscany
RESTful SCA with Apache Tuscany
Raymond Feng
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
Oleg Podsechin
 
Rack
RackRack
Rack
shen liu
 
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lightbend
 
Reactive streams processing using Akka Streams
Reactive streams processing using Akka StreamsReactive streams processing using Akka Streams
Reactive streams processing using Akka Streams
Johan Andrén
 
Scorex, the Modular Blockchain Framework
Scorex, the Modular Blockchain FrameworkScorex, the Modular Blockchain Framework
Scorex, the Modular Blockchain Framework
Alex Chepurnoy
 
BigDataSpain 2016: Stream Processing Applications with Apache Apex
BigDataSpain 2016: Stream Processing Applications with Apache ApexBigDataSpain 2016: Stream Processing Applications with Apache Apex
BigDataSpain 2016: Stream Processing Applications with Apache Apex
Thomas Weise
 
Building RESTful services using SCA and JAX-RS
Building RESTful services using SCA and JAX-RSBuilding RESTful services using SCA and JAX-RS
Building RESTful services using SCA and JAX-RS
Luciano Resende
 
Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
Konrad Malawski
 
Asynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsAsynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka Streams
Johan Andrén
 
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Kafka
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & KafkaBack-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Kafka
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Kafka
Akara Sucharitakul
 
Streaming all the things with akka streams
Streaming all the things with akka streams   Streaming all the things with akka streams
Streaming all the things with akka streams
Johan Andrén
 

Similar to Building scalable rest service using Akka HTTP (20)

Scala45 spray test
Scala45 spray testScala45 spray test
Scala45 spray test
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
Exploring Reactive Integrations With Akka Streams, Alpakka And Apache Kafka
Exploring Reactive Integrations With Akka Streams, Alpakka And Apache KafkaExploring Reactive Integrations With Akka Streams, Alpakka And Apache Kafka
Exploring Reactive Integrations With Akka Streams, Alpakka And Apache Kafka
 
Building REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with ScalaBuilding REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with Scala
 
Akka streams - Umeå java usergroup
Akka streams - Umeå java usergroupAkka streams - Umeå java usergroup
Akka streams - Umeå java usergroup
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
2 Asp Dot Net Ajax Extensions
2 Asp Dot Net Ajax Extensions2 Asp Dot Net Ajax Extensions
2 Asp Dot Net Ajax Extensions
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
 
RESTful SCA with Apache Tuscany
RESTful SCA with Apache TuscanyRESTful SCA with Apache Tuscany
RESTful SCA with Apache Tuscany
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Rack
RackRack
Rack
 
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
 
Reactive streams processing using Akka Streams
Reactive streams processing using Akka StreamsReactive streams processing using Akka Streams
Reactive streams processing using Akka Streams
 
Scorex, the Modular Blockchain Framework
Scorex, the Modular Blockchain FrameworkScorex, the Modular Blockchain Framework
Scorex, the Modular Blockchain Framework
 
BigDataSpain 2016: Stream Processing Applications with Apache Apex
BigDataSpain 2016: Stream Processing Applications with Apache ApexBigDataSpain 2016: Stream Processing Applications with Apache Apex
BigDataSpain 2016: Stream Processing Applications with Apache Apex
 
Building RESTful services using SCA and JAX-RS
Building RESTful services using SCA and JAX-RSBuilding RESTful services using SCA and JAX-RS
Building RESTful services using SCA and JAX-RS
 
Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
 
Asynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsAsynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka Streams
 
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Kafka
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & KafkaBack-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Kafka
Back-Pressure in Action: Handling High-Burst Workloads with Akka Streams & Kafka
 
Streaming all the things with akka streams
Streaming all the things with akka streams   Streaming all the things with akka streams
Streaming all the things with akka streams
 

More from datamantra

Multi Source Data Analysis using Spark and Tellius
Multi Source Data Analysis using Spark and TelliusMulti Source Data Analysis using Spark and Tellius
Multi Source Data Analysis using Spark and Tellius
datamantra
 
State management in Structured Streaming
State management in Structured StreamingState management in Structured Streaming
State management in Structured Streaming
datamantra
 
Understanding transactional writes in datasource v2
Understanding transactional writes in  datasource v2Understanding transactional writes in  datasource v2
Understanding transactional writes in datasource v2
datamantra
 
Exploratory Data Analysis in Spark
Exploratory Data Analysis in SparkExploratory Data Analysis in Spark
Exploratory Data Analysis in Spark
datamantra
 
Core Services behind Spark Job Execution
Core Services behind Spark Job ExecutionCore Services behind Spark Job Execution
Core Services behind Spark Job Execution
datamantra
 
Optimizing S3 Write-heavy Spark workloads
Optimizing S3 Write-heavy Spark workloadsOptimizing S3 Write-heavy Spark workloads
Optimizing S3 Write-heavy Spark workloads
datamantra
 
Understanding time in structured streaming
Understanding time in structured streamingUnderstanding time in structured streaming
Understanding time in structured streaming
datamantra
 
Spark stack for Model life-cycle management
Spark stack for Model life-cycle managementSpark stack for Model life-cycle management
Spark stack for Model life-cycle management
datamantra
 
Productionalizing Spark ML
Productionalizing Spark MLProductionalizing Spark ML
Productionalizing Spark ML
datamantra
 
Testing Spark and Scala
Testing Spark and ScalaTesting Spark and Scala
Testing Spark and Scala
datamantra
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
datamantra
 
Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2
datamantra
 
Scalable Spark deployment using Kubernetes
Scalable Spark deployment using KubernetesScalable Spark deployment using Kubernetes
Scalable Spark deployment using Kubernetes
datamantra
 
Introduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actorsIntroduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actors
datamantra
 
Interactive workflow management using Azkaban
Interactive workflow management using AzkabanInteractive workflow management using Azkaban
Interactive workflow management using Azkaban
datamantra
 
Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2
datamantra
 
Introduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset APIIntroduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset API
datamantra
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
datamantra
 

More from datamantra (18)

Multi Source Data Analysis using Spark and Tellius
Multi Source Data Analysis using Spark and TelliusMulti Source Data Analysis using Spark and Tellius
Multi Source Data Analysis using Spark and Tellius
 
State management in Structured Streaming
State management in Structured StreamingState management in Structured Streaming
State management in Structured Streaming
 
Understanding transactional writes in datasource v2
Understanding transactional writes in  datasource v2Understanding transactional writes in  datasource v2
Understanding transactional writes in datasource v2
 
Exploratory Data Analysis in Spark
Exploratory Data Analysis in SparkExploratory Data Analysis in Spark
Exploratory Data Analysis in Spark
 
Core Services behind Spark Job Execution
Core Services behind Spark Job ExecutionCore Services behind Spark Job Execution
Core Services behind Spark Job Execution
 
Optimizing S3 Write-heavy Spark workloads
Optimizing S3 Write-heavy Spark workloadsOptimizing S3 Write-heavy Spark workloads
Optimizing S3 Write-heavy Spark workloads
 
Understanding time in structured streaming
Understanding time in structured streamingUnderstanding time in structured streaming
Understanding time in structured streaming
 
Spark stack for Model life-cycle management
Spark stack for Model life-cycle managementSpark stack for Model life-cycle management
Spark stack for Model life-cycle management
 
Productionalizing Spark ML
Productionalizing Spark MLProductionalizing Spark ML
Productionalizing Spark ML
 
Testing Spark and Scala
Testing Spark and ScalaTesting Spark and Scala
Testing Spark and Scala
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
 
Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2
 
Scalable Spark deployment using Kubernetes
Scalable Spark deployment using KubernetesScalable Spark deployment using Kubernetes
Scalable Spark deployment using Kubernetes
 
Introduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actorsIntroduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actors
 
Interactive workflow management using Azkaban
Interactive workflow management using AzkabanInteractive workflow management using Azkaban
Interactive workflow management using Azkaban
 
Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2
 
Introduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset APIIntroduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset API
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
 

Recently uploaded

dachnug51 - All you ever wanted to know about domino licensing.pdf
dachnug51 - All you ever wanted to know about domino licensing.pdfdachnug51 - All you ever wanted to know about domino licensing.pdf
dachnug51 - All you ever wanted to know about domino licensing.pdf
DNUG e.V.
 
Addressing the Top 9 User Pain Points with Visual Design Elements.pptx
Addressing the Top 9 User Pain Points with Visual Design Elements.pptxAddressing the Top 9 User Pain Points with Visual Design Elements.pptx
Addressing the Top 9 User Pain Points with Visual Design Elements.pptx
Sparity1
 
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
Hironori Washizaki
 
dachnug51 - Whats new in domino 14 .pdf
dachnug51 - Whats new in domino 14  .pdfdachnug51 - Whats new in domino 14  .pdf
dachnug51 - Whats new in domino 14 .pdf
DNUG e.V.
 
Break data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud ConnectorsBreak data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud Connectors
confluent
 
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple StepsSeamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Estuary Flow
 
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdfIndependence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Livetecs LLC
 
Splunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptxSplunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptx
sudsdeep
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
sudsdeep
 
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
SimonedeGijt
 
ENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentationENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentation
sofiafernandezon
 
How we built TryBoxLang in under 48 hours
How we built TryBoxLang in under 48 hoursHow we built TryBoxLang in under 48 hours
How we built TryBoxLang in under 48 hours
Ortus Solutions, Corp
 
WEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service ProvidersWEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service Providers
Severalnines
 
Safe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work PermitsSafe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work Permits
sheqnetworkmarketing
 
introduction of Ansys software and basic and advance knowledge of modelling s...
introduction of Ansys software and basic and advance knowledge of modelling s...introduction of Ansys software and basic and advance knowledge of modelling s...
introduction of Ansys software and basic and advance knowledge of modelling s...
sachin chaurasia
 
ANSYS Mechanical APDL Introductory Tutorials.pdf
ANSYS Mechanical APDL Introductory Tutorials.pdfANSYS Mechanical APDL Introductory Tutorials.pdf
ANSYS Mechanical APDL Introductory Tutorials.pdf
sachin chaurasia
 
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdfdachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
DNUG e.V.
 
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
avufu
 
Intro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AIIntro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AI
Ortus Solutions, Corp
 

Recently uploaded (20)

dachnug51 - All you ever wanted to know about domino licensing.pdf
dachnug51 - All you ever wanted to know about domino licensing.pdfdachnug51 - All you ever wanted to know about domino licensing.pdf
dachnug51 - All you ever wanted to know about domino licensing.pdf
 
Addressing the Top 9 User Pain Points with Visual Design Elements.pptx
Addressing the Top 9 User Pain Points with Visual Design Elements.pptxAddressing the Top 9 User Pain Points with Visual Design Elements.pptx
Addressing the Top 9 User Pain Points with Visual Design Elements.pptx
 
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
 
dachnug51 - Whats new in domino 14 .pdf
dachnug51 - Whats new in domino 14  .pdfdachnug51 - Whats new in domino 14  .pdf
dachnug51 - Whats new in domino 14 .pdf
 
Break data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud ConnectorsBreak data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud Connectors
 
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple StepsSeamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
 
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdfIndependence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
 
Splunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptxSplunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptx
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
 
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
 
ENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentationENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentation
 
How we built TryBoxLang in under 48 hours
How we built TryBoxLang in under 48 hoursHow we built TryBoxLang in under 48 hours
How we built TryBoxLang in under 48 hours
 
WEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service ProvidersWEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service Providers
 
Safe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work PermitsSafe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work Permits
 
introduction of Ansys software and basic and advance knowledge of modelling s...
introduction of Ansys software and basic and advance knowledge of modelling s...introduction of Ansys software and basic and advance knowledge of modelling s...
introduction of Ansys software and basic and advance knowledge of modelling s...
 
ANSYS Mechanical APDL Introductory Tutorials.pdf
ANSYS Mechanical APDL Introductory Tutorials.pdfANSYS Mechanical APDL Introductory Tutorials.pdf
ANSYS Mechanical APDL Introductory Tutorials.pdf
 
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdfdachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
 
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
 
Intro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AIIntro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AI
 

Building scalable rest service using Akka HTTP

  • 1. Introduction to Akka HTTP Building scalable rest service in Scala https://github.com/shashankgowdal/introduction-to-akkahttp
  • 2. ● Shashank L ● Senior Software engineer at Tellius ● Part time big data consultant and trainer at datamantra.io ● www.shashankgowda.com
  • 3. Agenda ● Motivation ● Akka, Reactive streams ● Akka Http ● Akka Http High level API ● Testing ● Additional functionality ● Working with files ● Websockets ● Akka Http with Spark
  • 4. Scala frameworks to build REST API ● Play/Lift ○ Full stack web framework ● Scalatra ○ Lightweight but requires a application container for deployment ● Spray ○ Lightweight and robust as it's asynchronous and built on top of Actors ● Akka HTTP ○ Next version of Spray framework
  • 5. Why Akka HTTP ● Its 2.0 version of Spray.io ● Internals of Spray have been rewritten to use Reactive streams ● Reactive streams idea gel well with earlier ideas of Spray ● Multiple level API
  • 6. Akka ● Toolkit and runtime for building highly concurrent, distributed, and fault tolerant applications on the JVM ● Uses message passing based concurrency model ● Written in Scala ● Scale up or out ● Program at higher level ● Distributable by design ● Message passing is built on top of AkkaActor model
  • 7. Akka actor ● Receives message and takes action to handle them ● Consists of ○ Behaviour ○ State ○ Mailbox
  • 8. Reactive streams ● Asynchronous ● Stream processing ● Back-pressured ● Interoperability ● Few Implementations ○ Akka Streams ○ RxJava ○ Play ○ Kafka ● Spark streaming with Kafka receiver
  • 9. Akka streams ● Akka’s implementation of Reactive streams ● DSL for building a complete stream ● Higher level abstraction over the actor model ● Stream inputs and outputs are typesafe ● Internally uses Actor to implement Reactive stream properties
  • 11. Source, Flow and Sink com.shashank.akkahttp.IntroductionToStream implicit val sys = ActorSystem("IntroductionToStream") implicit val mat:Materializer = ActorMaterializer() val source = Source(List(1, 2, 3)) val flow = Flow[Int].map(_.toString) val sink = Sink.foreach(println) val runnableGraph = source via flow to sink runnableGraph.run()
  • 12. HTTP server with Akka streams HTTPServer as a: Flow[HttpRequest, HttpResponse] Socket input Bytes ⇒ HttpRequest HttpRequest ⇒ HttpResponse HttpResponse ⇒ Bytes Socket Sink
  • 13. Akka Http server using Flow implicit val sys = ActorSystem("IntroductionToAkkaHttp") implicit val mat:Materializer = ActorMaterializer() val requestResponseFlow = Flow.fromFunction[HttpRequest, HttpResponse]( request => { println(request.toString) HttpResponse(StatusCodes.OK, entity = "Hello!") }) Http().bindAndHandle(requestResponseFlow, "localhost", 8080) com.shashank.akkahttp.basic.serving.StreamsServing
  • 14. Akka HTTP ● Part of Akka project ● HTTP toolkit (Client and Server) ● On top of akka-actor and akka-streams ● Multiple levels of abstraction - Open API ● Scalable, Max throughput, acceptable latency ● APIs in both Scala and Java
  • 15. Akka HTTP - Implementation ● Fully asynchronous and nonblocking ● Focused on higher level API ● Lightweight ● Modular ● Testable ● Based on spray.io ● Better streaming REST functionality support
  • 17. Akka HTTP structure Akka HTTP module akka-http akka-http-core akka-http-testkit akka-http- spray-json akka-http-xml
  • 18. Akka HTTP - Parts ● akka-http-core ○ low-level server & client side HTTP implementation ● akka-http ○ high-level API : DSL, (un)marshalling, (de)compression ● akka-http-testkit ○ Utilities for testing server-side implementation ● akka-http-spray-json ○ (de)serialization from/to JSON with spray-json ● akka-http-xml ○ (de)serialization from/to XML with scala-xml
  • 19. HTTP model ● Fully immutable, case-class based ● Abstraction for most HTTP things (Types!) ● Little logic inside ● Lots of predefined types - media type, status code, encodings etc ● Efficient parsing and rendering ● Clients/Connected services should obey the standard
  • 20. HTTP model - Examples case class HttpRequest(method: HttpMethod = HttpMethods.GET, uri: Uri = Uri./, headers: immutable.Seq[HttpHeader] = Nil, entity: RequestEntity = HttpEntity.Empty, protocol: HttpProtocol = HttpProtocols.`HTTP/1.1`) case class HttpResponse(status: StatusCode = StatusCodes.OK, headers: immutable.Seq[HttpHeader] = Nil, entity: ResponseEntity = HttpEntity.Empty, protocol: HttpProtocol = HttpProtocols.`HTTP/1.1`) case class Uri(scheme: String, authority: Authority, path: Path, rawQueryString: Option[String], fragment: Option[String])
  • 21. HTTP model - Examples object ContentTypes { val `application/json` = ContentType(MediaTypes.`application/json`) val `application/octet-stream` = ContentType(MediaTypes.`application/octet-stream`) val `text/plain(UTF-8)` = MediaTypes.`text/plain` withCharset HttpCharsets.`UTF-8` val `text/html(UTF-8)` = MediaTypes.`text/html` withCharset HttpCharsets.`UTF-8` val `text/xml(UTF-8)` = MediaTypes.`text/xml` withCharset HttpCharsets.`UTF-8` val `text/csv(UTF-8)` = MediaTypes.`text/csv` withCharset HttpCharsets.`UTF-8` val NoContentType = ContentType(MediaTypes.NoMediaType) } val `US-ASCII` = register("US-ASCII")("iso-ir-6", "ANSI_X3.4-1968", "ANSI_X3.4-1986", "ISO_646.irv:1991", "ASCII", "ISO646-US", "us", "IBM367", "cp367", "csASCII") val `ISO-8859-1` = register("ISO-8859-1")("iso-ir-100", "ISO_8859-1", "latin1", "l1", "IBM819", "CP819", "csISOLatin1") val `UTF-8` = register("UTF-8")("UTF8") val `UTF-16` = register("UTF-16")("UTF16") val `UTF-16BE` = register("UTF-16BE")() val `UTF-16LE` = register("UTF-16LE")()
  • 22. HTTP server functional way ● Low level HTTP API ● Provided by akka-http-core-module implicit val sys = ActorSystem("IntroductionToAkkaHttp") implicit val mat:Materializer = ActorMaterializer() val handler :(HttpRequest => HttpResponse) = { case HttpRequest(HttpMethods.GET, Uri.Path("/ping"), _, _, _) => HttpResponse(StatusCodes.OK, entity = "pong!") case r => HttpResponse(status = StatusCodes.BadRequest) } Http().bindAndHandleSync(handler, "localhost", 8080) com.shashank.akkahttp.basic.serving.FunctionalServing
  • 23. Akka Http high level API
  • 24. HTTP Server Nice way! ��� Low level API becomes uneasy to handle when we need large number of routes ● For this we should use higher level API by akka-http ● Route using Routing DSL implicit val sys = ActorSystem("IntroductionToAkkaHttp") implicit val mat:Materializer = ActorMaterializer() val routes: Route = ??? Http(sys).bindAndHandle(route, "localhost", 8090)
  • 25. Routing DSL ● Internal domain specific language for routing ● How most services are actually written ● Layer to the application ● Type safe but flexible ● Not just routing - behaviour definition ● Very composable ● Fun, powerful and looks clean
  • 26. Routing DSL - Example val route = path("welcome"){ get{ complete { "welcome to rest service" } } } ~ path("demo"){ get{ complete { "welcome to demonstration" } } } Http().bindAndHandle(route, "localhost", 8090) com.shashank.akkahttp.basic.routing.RoutingDSL
  • 27. Directives ● A Directive is a small building block used for creating routes. ● There are some predefined directives( get, post, complete etc.) ● We can also define our custom directives. ● Roles: extracting, transforming request or response, filtering, side-effecting ● ~136 predefined directives
  • 28. Rejections ● Produced by directives ● Travel down the routing structure ● EmptyRejection is thrown when no route completes ● Can be extended ● Can be cancelled ● Handling rejection = transforming it to response ● Ex. MethodRejection, AuthorizationFailedRejection, MissingCookieRejection, MissingQueryParamRejection
  • 29. Rejections ● ~ operator connects two routes in a way that allows a second route to get a go at a request if the first route "rejected" it. path("order") { get { complete("Received GET") } ~ post { complete("Received POST") } } com.shashank.akkahttp.basic.routing.Rejection
  • 30. Failures ● Are triggered by exceptions ● Travel up the routing structure ● Can be handled by handleExceptions directive or top-level ExceptionHandler ● Can be used to simplify the flow for validation purpose com.shashank.akkahttp.basic.routing.Failure
  • 32. ● Simple and straightforward ● Allows to assert responses returned for given requests ● Integrates well with Scalatest Get("/ping") ~> route ~> check{ status === OK entity.as[String] === "It Works!" } com.shashank.akkahttp.basic.routing.TestKit Testkit
  • 34. Query parameters def parameters(param: <ParamDef[T]>): Directive1[T] ● Mandatory parameters ● Optional parameters ● Parameters with required value ● Deserialized parameter ● Repeated parameter ● Deserialized parameter into Case class
  • 35. (Un)Marshalling ● Marshalling - high level → low (wire) level ● Unmarshalling - low (wire) level → high level ● Many predefined (un) marshallers are available ● Extensible ● JSON and XML supported ● Type-class approach - Implicit resolution
  • 36. Custom Http entity data ● Akka Http JSON support ● Support conversion to and from JVM objects to wire representation like JSON, XML etc ● SprayJsonSupport provides a FromEntityUnmarshaller[T] and ToEntityMarshaller[T] for every type T with Spray Json Reader/Writer com.shashank.akkahttp.basic.routing.CustomEntityWithJson
  • 37. Custom directive ● Configuration labelling ● Transforming existing directives ● Directive0, Directive1 ● Authorization ● Authentication com.shashank.akkahttp.basic.routing.CustomDirective
  • 39. File upload def uploadedFile(fieldName: String): Directive1[(FileInfo, File)] ● Streams the contents of a file uploaded as a multipart form into a temporary file on disk ● Cannot start processing the file unless it written completely to temporary file com.shashank.akkahttp.basic.routing.FileUpload
  • 40. File upload stream def fileUpload(fieldName: String): Directive1[(FileInfo, Source[ByteString, Any])] ● Simple access to the stream of bytes for a file uploaded as a multipart form together with metadata about the upload as extracted value. com.shashank.akkahttp.basic.routing.FileUploadStream
  • 42. Websocket ● WebSocket is a protocol that provides a bi-directional channel between browser and webserver ● Data is exchanged in messages whereby a message can either be binary data or unicode text
  • 43. Server side websocket in AkkaHttp ● Akka HTTP provides a stream-based implementation of the WebSocket protocol ● basic unit of data exchange in the WebSocket is a message i.e TextMessage or BinaryMessage ● Websocket handshake is managed and hidden from application layer ● A message handler is expected to be implemented as a Flow[Message, Message, Any] ● Testing Websocket using WSProbe com.shashank.akkahttp.basic.routing.Websocket
  • 44. Akka HTTP with Spark Spark Cluster Akka Http Rest server Client HDFS
  • 45. Pros and Cons ● Pros ○ Backed by Lightbend(Typesafe) ○ Integration layers ○ Microservices ○ Pure REST APIs ● Cons ○ Full fledged web applications (server side template generation) ○ Not mature enough ○ Easy to start, hard to master
  • 46. References ● Akka HTTP - A reactive web toolkit ● Akka HTTP - What, Why and How ● Introduction to Akka HTTP ● Akka HTTP documentation http://doc.akka.io/docs/akka/2.4.2/scala/http/ ● http://blog.madhukaraphatak.com/categories/akka-http/