A Look at Serverless Architectures
What is a "serverless architecture" and why would you use one? Read on to find out.
Join the DZone community and get the full member experience.Join For Free
one of the latest architectural styles to appear on the internet is that of serverless architectures, which allow teams to get rid of the traditional server engine that sits behind their web and mobile applications. mike roberts has been working with teams that have using this approach and has started writing an evolving article to explain this style and how to use it. he begins with describing what "serverless" means — with a couple of examples of how more usual designs become serverless.
like many trends in software, there's no one clear view of what "serverless" is, and that isn't helped by it really coming to mean two different but overlapping areas:
- serverless was first used to describe applications that significantly or fully depend on third-party applications/services ("in the cloud") to manage server-side logic and state. these are typically "rich client" applications (think single page web apps, or mobile apps) that use the vast ecosystem of cloud accessible databases (like parse, firebase), authentication services (auth0, aws cognito), etc. these types of services have been previously described as " (mobile) backend as a service ," and i'll be using " baas" as a shorthand in the rest of this article.
- serverless can also mean applications where some amount of server-side logic is still written by the application developer but, unlike traditional architectures, is run in stateless compute containers that are event-triggered, ephemeral (may only last for one invocation), and fully managed by a third-party. (thanks to thoughtworks for their definition in their most recent tech radar .) one way to think of this is " functions as a service /faas." aws lambda is one of the most popular implementations of faas at present, but there are others. i'll be using " faas" as a shorthand for this meaning of serverless throughout the rest of this article.
mostly i'm going to talk about the second of these areas because it is the one that is newer, has significant differences to how we typically think about technical architecture, and has been driving a lot of the hype around serverless.
however, these concepts are related and, in fact, converging. a good example is auth0 — they started initially with baas "authentication as a service," but with auth0 webtask , they are entering the faas space.
furthermore, in many cases, when developing a "baas-shaped" application, especially when developing a "rich" web-based app as opposed to a mobile app, you'll likely still need some amount of custom server-side functionality. faas functions may be a good solution for this, especially if they are integrated to some extent with the baas services you’re using. examples of such functionality include data validation (protecting against imposter clients) and compute-intensive processing (e.g. image or video manipulation.)
a couple of examples
let’s think about a traditional 3-tier client-oriented system with server-side logic. a good example is a typical ecommerce app (dare i say an online pet store?)
with this architecture, the client can be relatively unintelligent, with much of the logic in the system — authentication, page navigation, searching, transactions — implemented by the server application.
with a serverless architecture, this may end up looking more like this:
this is a massively simplified view, but even with this there are a number of significant changes that have happened here. please note this is not a recommendation of an architectural migration, i’m merely using this as a tool to expose some serverless concepts!
- we’ve deleted the authentication logic in the original application and have replaced it with a third-party baas service.
- using another example of baas, we’ve allowed the client direct access to a subset of our database (for product listings), which itself is fully third-party hosted (e.g. aws dynamo.) we likely have a different security profile for the client accessing the database in this way from any server resources that may access the database.
- these previous two points imply a very important third — some logic that was in the pet store server is now within the client, e.g. keeping track of a user session, understanding the ux structure of the application (e.g. page navigation), reading from a database and translating that into a usable view, etc. the client is in fact well on its way to becoming a single page application .
- some ux related functionality we may want to keep in the server, e.g. if it's compute intensive or requires access to significant amounts of data. an example here is "search." for the search feature, instead of having an always-running server we can implement a faas function that responds to http requests via an api gateway (described later.) we can have both the clientand the server function read from the same database for product data.
- because the original server was implemented in java, and aws lambda (our faas vendor of choice in this instance) supports functions implemented in java, we can port the search code from the pet store server to the pet store search function without a complete re-write.
- finally, we may replace our "purchase" functionality with another faas function, choosing to keep it on the server side for security reasons, rather than re-implement it in the client. it, too, is fronted by api gateway.
a different example is a backend data-processing service. say you're writing a user-centric application that needs to quickly respond to ui requests, but secondarily you want to capture all the different types of activity that are occurring. let's think about an online ad system — when a user clicks on an advertisement, you want to very quickly redirect them to the target of the ad, but at the same time, you need to collect the fact that the click has happened so that you can charge the advertiser.
traditionally, the architecture may look like this. the "ad server" synchronously responds to the user — we don’t care about that interaction for the sake of this example — but it also posts a message to a channel that can be asynchronously processed by a "click processor" application that updates a database, e.g. to decrement the advertiser’s budget.
in the serverless world this looks like:
there’s a much smaller difference to the architecture here compared to our first example. we’ve replaced a long-lived consumer application with a faas function that runs within the event driven context the vendor provides us. note that the vendor supplies both the message broker and the faas environment — the two systems are closely tied to each other.
the faas environment may also process several clicks in parallel by instantiating multiple copies of the function code — depending on how we'd written the original process this may be a new concept we need to consider.
unpacking "function as a service"
we've mentioned the faas idea a lot already, but it's time to dig into what it really means. to do this let's look at the opening description for amazon's lambda product. i've added some tokens to it, which i then expand upon.
- fundamentally faas is about running back-end code without managing your own server systems or your own server applications. that second clause — server applications — is a key difference when comparing with other modern architectural trends like containers and paas (platform as a service.)
- if we go back to our click processing example from earlier, what faas does is replace the click processing server (possibly a physical machine, but definitely a specific application) with something that doesn’t need a provisioned server, nor an application that is running all the time.
- let’s consider our click processing example again — the only code that needs to change when moving to faas is the "main method / startup" code, in that it is deleted, and likely the specific code that is the top-level message handler (the "message listener interface" implementation), but this might only be a change in method signature. all of the rest of the code (e.g. the code that writes to the database) is no different in a faas world.
- since we have no server applications to run deployment is very different to traditional systems — we upload the code to the faas provider and it does everything else. right now that typically means uploading a new definition of the code (e.g. in a zip or jar file), and then calling a proprietary api to initiate the update.
- horizontal scaling is completely automatic, elastic, and managed by the provider. if your system needs to be processing 100 requests in parallel the provider will handle that without any extra configuration on your part. the "compute containers" executing your functions are ephemeral with the faas provider provisioning and destroying them purely driven by runtime need.
- let's return to our click processor. say that we were having a good day and customers were clicking on 10 times as many ads as usual. would our click processing application be able to handle this? for example, did we code to be able to handle multiple messages at a time? even if we did, would one running instance of the application be enough to process the load? if we are able to run multiple processes, is auto-scaling automatic or do we need to reconfigure that manually? with faas, you need to write the function ahead of time to assume parallelism, but from that point on the faas provider automatically handles all scaling needs.
- functions in faas are triggered by event types defined by the provider. with amazon aws such stimuli include s3 (file) updates, time (scheduled tasks), and messages added to a message bus (e.g. kinesis ). your function will typically have to provide parameters specific to the event source it is tied to. with the click processor, we made an assumption that we were already using a faas-supported message broker. if not, we would have needed to switch to one, and that would have required making changes to the message producer too.
- most providers also allow functions to be triggered as a response to inbound http requests, typically in some kind of api gateway. (e.g. aws api gateway , webtask ). we used this in our pet store example for our "search" and "purchase" functions.
faas functions have significant restrictions when it comes to local (machine/ nstance bound) state. in short, you should assume that for any given invocation of a function, none of the in-process or host states that you create will be available to any subsequent invocation. this includes state in ram and state you may write to local disk. in other words, from a deployment-unit point of view, faas functions are stateless .
this has a huge impact on application architecture, albeit not a unique one — the "twelve-factor app" concept has precisely the same restriction .
given this restriction, what are alternatives? typically it means that faas functions are either naturally stateless — i.e. they provide pure functional transformations of their input — or that they make use of a database, a cross-application cache (e.g. redis), or network file store (e.g. s3) to store state across requests or for further input to handle a request.
faas functions are typically limited in how long each invocation is allowed to run. at present aws lambda functions are not allowed to run for longer than 5 minutes, and if they do, they will be terminated.
this means that certain classes of long-lived task are not suited to faas functions without re-architecture, e.g. you may need to create several different coordinated faas functions where in a traditional environment you may have one long duration task performing both coordination and execution.
at present, how long it takes your faas function to respond to a request depends on a large number of factors, and may be anywhere from 10ms to 2 minutes. that sounds bad, but let's get a little more specific, using aws lambda as an example.
if your lambda function is implemented on the jvm, you may occasionally see long response times (e.g. > 10 seconds) while the jvm is spun up. however this only notably happens with either of the following scenarios:
- your function processes events infrequently, on the order of longer than 10 minutes between invocations.
- you have very sudden spikes in traffic, for instance, you typically process 10 requests per second but this ramps up to 100 requests per second in less than 10 seconds.
the former of these may be avoided in certain situations by the ugly hack of pinging your function every 5 minutes to keep it alive.
are these issues a concern? it depends on the style and traffic shape of your application. my former team has an asynchronous message-processing lambda app implemented in java which processes hundreds of millions of messages/day, and they have no concerns with startup latency. that said, if you were writing a low-latency trading application you probably wouldn’t want to use faas systems at this time, no matter the language you were using for implementation.
whether or not you think your app may have problems like this, you should test with production-like load to see what performance you see. if your use case doesn't work now, you may want to try again in a few months time since this is a major area of development by faas vendors.
one aspect of faas that we brushed upon earlier is an "api gateway." an api gateway is an http server where routes/endpoints are defined in configuration and each route is associated with a faas function. when an api gateway receives a request, it finds the routing configuration matching the request and then calls the relevant faas function. typically, the api gateway will allow mapping from http request parameters to inputs arguments for the faas function. the api gateway transforms the result of the faas function call to an http response and returns this to the original caller.
amazon web services have their own api gateway and other vendors offer similar abilities.
beyond purely routing requests, api gateways may also perform authentication, input validation, response code mapping, etc. your spidey-sense may be buzzing about whether this is actually such a good idea, if so hold that thought -—we'll consider this further later.
one use case for api gateway + faas is for creating http-fronted microservices in a serverless way with all the scaling, management and other benefits that come from faas functions.
at present, tooling for api gateways is achingly immature and so while defining applications with api gateways is possible, it's most definitely not for the faint-hearted.
the comment above about api gateway tooling being immature actually applies, on the whole, to serverless faas in general. there are exceptions, however — one example is auth0 webtask , which places significant priority on developer ux in its tooling. tomasz janczuk gave a very good demonstration of this at the recent serverless conference.
debugging and monitoring are tricky in general in serverless apps — we’ll get into this further in subsequent installments of this article.
one of the main benefits of serverless faas applications is transparent production runtime provisioning, and so open source is not currently as relevant in this world as it is for, say, docker and containers. in the future, we may see a popular faas/api gateway platform implementation that will run "on premise" or on a developer workstation. ibm’s openwhisk is an example of such an implementation, and it will be interesting to see whether this, or an alternative implementation, picks up adoption.
another example is apex — a project to "build, deploy, and manage aws lambda functions with ease." one particularly interesting aspect of apex is that it allows you to develop lambda functions in languages other than those directly supported by amazon, e.g. go.
what isn’t serverless?
so far in this article i've defined "serverless" to mean the union of a couple of other ideas — "backend as a service" and "functions as a service." i've also dug into the capabilities of the second of these.
before we start looking at the very important area of benefits and drawbacks, i'd like to spend one more moment on definition, or at least defining what serverless isn't. i’ve seen some people (including me in the recent past) get confused about these things, and i think it's worth discussing them for clarity's sake.
comparison with paas
given that serverless faas functions are very similar to 12-factor applications, are they in fact just another form of "platform as a service" (paas) like heroku ? for a brief answer, i refer to adrian cockcroft:
in other words, most paas applications are not geared towards bringing entire applications up and down for every request, whereas faas platforms do exactly this.
ok, but so what, if i'm being a good 12-factor app developer, there's still no difference to how i code? that's true, but there is a big difference to how you operate your app. because we're all good devops-savvy engineers, we're thinking about operations as much as we are about development, right?
the key operational difference between faas and paas is scaling . with most paass you still need to think about scale, e.g. with heroku how many dynos you want to run. with a faas application, this is completely transparent. even if you set up your paas application to auto-scale, you won't be doing this to the level of individual requests (unless you have a very specifically shaped traffic profile), and so a faas application is much more efficient when it comes to costs.
given this benefit, why would you still use a paas? there are several reasons, but tooling and maturity of api gateways are probably the biggest. furthermore, 12-factor apps implemented in a paas may use an in-app readonly cache for optimization, which isn't an option for faas functions.
serverless doesn't mean "no ops." it might mean "no internal sys admin," depending on how far down the serverless rabbit hole you go. there are two important things to consider here.
firstly "ops" means a lot more than server administration. it also means at least monitoring, deployment, security, networking, and often also means some amount of production debugging and system scaling. these problems all still exist with serverless apps, and you're still going to need a strategy to deal with them. in some ways, ops is harder in a serverless world because a lot of this is so new.
second even the sys admin is still happening — you're just outsourcing it with serverless. that's not necessarily a bad thing — we outsource a lot. but depending on what precisely you're trying to do, this might be a good or a bad thing, and either way, at some point the abstraction will likely leak and you'll need to know that human sys admins somewhere are supporting your application.
stored procedures as a service
another theme i've seen is that serverless faas is "stored procedures as a service." i think that's come from the fact that many examples of faas functions (including some i've used in this article) are small pieces of code that wrap access to a database. if that's all we could use faas for i think the name would be useful, but because it is really just a subset of faas's capability, then thinking of faas in such a way is an invalid constraint.
that being said it is worth considering whether faas comes with some of the same problems of stored procedures, including the technical debt concern camille mentions in the referenced tweet. there are many lessons that come from using stored procs that are worth reviewing in the context of faas and seeing whether they apply. some of these are that stored procedures:
- often require vendor-specific language, or at least vendor-specific frameworks/extensions to a language.
- are hard to test because they need to be executed in the context of a database.
- are tricky to version control/treat as a first class application.
note that not all of these may apply to all implementations of stored procs, but they're certainly problems that i've come across in my time. let’s see if they might apply to faas:
(1) is definitely not a concern for the faas implementations i’ve seen so far, so we can scrub that one off the list right away.
for (2), because we're dealing with "just code," unit testing is definitely just as easy as any other code. integration testing is a different (and legitimate) question though which we'll discuss later.
for (3), again since faas functions are ‘just code’ version control is ok. but as for application packaging, there are no mature patterns on this yet. the sserverless framework i mentioned earlier does provide its own form of this, and aws announced at the recent serverless conference in may 2016 that they are working on something for packaging also ("flourish"), but for now this is another legitimate concern.
this is an evolving publication, and i shall be extending it over the coming days and weeks to cover more topics on serverless architecture including the benefits and drawbacks of this approach, and where we might see serverless evolve over the next year or two.
Published at DZone with permission of Mike Roberts. See the original article here.
Opinions expressed by DZone contributors are their own.