1. Home
  2. Explore
  3. Computer Science
  4. Resilient Application Design Patterns

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Resilient Application Design Patterns

Transcript

- Hi everybody, my name's Derek Bingham. I'm a developer advocate at AWS and welcome to today's talk. All about five design patterns to build resilient applications. So today, over the next 35, 40 minutes, I'm going to go through an application, and I'm gonna show you what patterns you can use to implement and build out a more resilient application framework. So as well as that, I'll just say upfront that I apologize for all the really bad jokes you'll hear today.

You'll know more of what I mean, as we go into this talk. Also, we'll have live Q&A. So if you've got any burning questions about what I'm talking about today, please enter them into the chat and we will respond as we go. So without any further ado, let's get into it. Oh yeah, so let's start with a quote.

So the quote I have for you today is from Dr Werner Vogels, our CTO at Amazon. "Failures are given and everything will eventually fail over time." So when I talk about this quote, I talk about it in terms of how to build out your modern, distributed cloud native applications. Whereas as you build them, you inevitably go over different pieces of hardware, different networks, using different stacks

to build out those applications. And in any one of those components can fail out of time. Now, this isn't a bad thing. This is actually asking you, when you're building and designing that application, to think about the failure modes that, that application will have to adopt with, and grow with over time. So that when a particular component does go down, as it inevitably will, all your application can re:Cover and continue to serve its users.

So today, that's exactly what I'm going to do. I'm going to show you five patterns that you can implement to make that distributed application resilient to failure. I'm also going to show you one practice. So the patterns I'm gonna show you are timeouts, graceful degradation, retries, exponential backoff and circuit breakers. And the one practice I'll show you at the end is chaos engineering. Let's start by meeting the application that we're going to build today.

So here I have .NET application, and the .NET application itself is already running in JetBrains Rider here. So my IDE of choice is JetBrains Rider. If I have a look at the application itself, you can see that up in the top left, I'm gonna scroll there, we've got react app inside the client app folder. And inside that source directory, I have got a component directory and inside that fetch data JS. So this is the main component of my react app. So the fetch data JS, got constructors,

got a table in it that renders jokes, more on jokes in a second. And if you scroll down a little bit more, you'll see there's a button and some contents. But the really important function is this populate joke data. You'll see that the function ultimately calls an api/Joke endpoint, gets rid of some response in JSON and then renders that response. So that is the react app. Also, we have an API. So this is what the react app is hitting. It's .NET controller. It defines a joke client.

And in the joke client is, if we have a look at it now, defines a "JOKE URL." So this is a third party joke API that this client calls. And in here, we've got an HttpClient, which is how.net, those rest calls. It hits the joke API, gets a response in JSON, and then serializes that JSON back out to the react app. Now, the serialized JSON, this is the object that it's serializing. It's got a joke and it's got set up, punchline, and source. And we'll go more into that in a second. So this is the app running. So this is my little react app. Why are monkeys great at sports? They're born chimpions. And if I hit re:Fresh, it'll give me another joke. What's the object-oriented way to become wealthy? Inheritance, of course. And then finally, how many programmers does it take to change a light bulb?

None, it's a hardware problem. As well as the UI, here's my API. So I'm showing you what the little joke client is hitting, and it comes back with the joke as part of the setup, the punchline, and the source. Currently the source is always going to be third party API 'cause that is what I'm hitting. So that's the application that I'm building. So let's go start applying some of our patterns to this architecture. So the architecture itself, you can see has a react application. Their react application hits the .NET microservice, the controller with the joke client. That then acts as a proxy into a 3rd party joke API, which could be running locally on my machine, it could be running in the cloud somewhere, that serves me back jokes back to my .NET microservice,

and then proxies that back to my react application that renders the joke. So that's all well and good, but what happens if my 3rd party joke API runs into some issues? And today we're gonna simulate those issues by having some random failures inserted into joke API. So what's what will happen typically? Well, a client will make a request into .NET microservice. That will then proxy that request into the 3rd party joke API. And it'll just sit there waiting re:Try but that will just sit there. And then of course the react web application

would sit there as well, just waiting for that response. So maybe another client will put another request into my .NET microservice, which again will proxy that into the 3rd party Joke API, which is already under load. So that would then delay that response, which would delay that response. And then ultimately, it would bring down my .NET microservice as well. And then the client would inevitably make another request into the .NET microservice, which is itself under load, and is not very happy because of all the requests that are waiting.

So a first pattern that we can try to negate this sort of problem happening is timeouts. So let's go back into the code and build out what timeouts would look like. How about zooming that so you can see, go into the code here and let's see what we can take. So, the first thing I need to do is I need to add a timeout, to the Http Client. I do this in .NET by just adding a property to the Http Client. And the property in this case is called timeout. The timeout itself, I can sit for a time span, but this one it makes sense to go at times by not zero but of seconds.

And for this, I'll probably set a time span of five seconds. So what this is doing, it's basically saying that for this client then have a timeout after five seconds. So if I do a request, how many programmers does it take to change a light bulb? And if I hit that request, if the request takes longer than five seconds, it will time out. So here it didn't take longer than five. So I got a response back from a 3rd party API. If I do it again, loading may take more than five seconds this time.

It has, so that the UI is actually frozen, at the width for response. But then if I see what's happening in my .NET microservice, if I do re:Fresh a couple of times, it's coming back from a third party API, okay. But then boof! What I get is a timeout exception. So what's happened here is my .NET microservice is requested my third party joke, and after five seconds it's timed out. So that is how to implement timeouts. Now timeouts in themselves are quite a rudimentary way of handling the API. So how I can... the next pattern, that I'm gonna call is pattern one A, how can I go about improving the timeouts? So currently the timeout that we're seeing is just spitting an exception

that we're not handling in the UI, but how can we get more control over that particular timeout? So let's go into the next pattern and get more control over that timeout. So back into my code again. So this time I'm going to get rid of the original, I call it the simple timeout, put the client code back to the way it was. And for this one, I'm going to start using a library, is the .NET library called Polly. So Polly is a resiliency library that we can use. So every language author will have a resilience library. Polly is just the one for .NET. There's a resiliency for J, if you want to use Java and the other languages have a similar library. So in Polly I'm gonna set a timeout and a synchronous timeout, I'd have again, five seconds.

But now I'm going to wrap, my request and response code and then anonymous in their function. So if I go policy.ExecuteAsync, and then inside that I'm gonna have an anonymous async function, which is gonna have a cancellation token. So CT, I'm going to define as my cancellation token. So what it's doing is I can cancel individual tasks with inside this anonymous function. So all I'm doing now is pulling that code up into my function like so, and just finished up the Indian thing here too. And so now this function is gonna execute, but I needed to find my cancellation token. That'll give me the control over async task,

within this function. So get async. You can have a CT cancellation token as can the response. So I can control that cancellation token and give you a bit more granularity of control inside that timeout. If I go back and rerun this application, you'll see what that look like. The backend inside my Joke API, once it spins up,

he will say that, why are monkeys great at sports? they are definitely born chimpions. Tell me another and re:Fresh, re:Fresh. Oh, came back within five, refresh again and we go back. and this just refresh this for ASCO. They'll coming back really, really quickly now. I was away, so my third party API, which you remember I've put in a random delay. and here we go, it's greater than five seconds. So we get this delegate executed asynchronusly throughout the TimeoutPolicy.

So it did not complete within the timeout. So again, the exception is in code 'cause I'm demonstrating it here, but it gives you a better granularity of control over the timeout. So that is two ways that you can do timeouts. Either by using a timeout within the Http Client itself for the parameter, or by using a third party library, like Polly and what we'll do for the rest of these patterns, we'll continue to build out how we can use Polly to satisfy them.

That next is pattern two. So pattern two is called graceful degradation. The code, expand that a little bit like so, Now let's build what the graceful degradation will look like using a polly library. So, from polly, the next thing I need to do is I'm going to define a fallback policy. So what a fallback policy is, is the policy that Polly will call if my reasonably policy, so it's an exception. So this fallback policy will return me a list of jokes. So I am the removal is a list of jokes. And what it has to do is has to handle a type of exception. So I'm gonna be very generic here and say, handle exception.

Generic exception, once I've defined the exception is gonna handle. The next thing I will need to do is say, okay, what am I going to do when I fall back? So this is the fallback async method, and I'm going to find, again, this takes an enumerable. So I list, I'm just going to tally this up so you can see it. And next line again, this takes enumerable of jokes and inside the fallback async, I'm gonna do another anonymous function. And inside this anonymous function, I'm gonna return a joke or a fallback joke. So what this is doing is, again, async the cancellation token into anonymous function,

into new list of jokes. And for this list, I'm gonna, for the sake of everybody watching my typing only have one joke, to be returned. And so if you remember, my joke object has a punchline. It also has a setup, and it has a source. So you will find those inside my joke object, set up is a string, punchline is also a string, and then source is a string consistent.

So let's think of a joke. Another marvelous joke. So let's have a band joke. So I'm in a band it's called 1023 megabytes. "We haven't had a gig yet", My source is gonna be fallback. So this is gonna show us in the UI, when we have hit the fallback.

So next thing I need to do is I need to pass that policy into a wrapper. So the policy wrapper is, Where I can pass different policies, almost chin them in an order of precedence. So while I've got a wrap, async is the fallback policy, which I've done there. Then inside that I will wrap up the policy.

And so now the policy fields is through an exception. We should then get the fallback policy. And the last thing I'm doing, I need to pass the policy wrapper to the execute async. The once that's done, we are gonna gracefully degrade the API. So the endpoint, so let's refresh the page. Let's do so how are hard things in computer science, cache invalidation right things, and that. We re:Fresh again they load for five seconds. Oh, here we go, fallback. So I'm in a band called 1023. We haven't had any gigs yet. And that's a source of fallback. Refreshing the backend to see what happens. The API calls, again, then there we go.

We're coming to fallback. So as you can see, we fresh. If we hit more than five seconds, we show the fallback. If we hit again, the API is working. We get a normal response. If we re:Fresh again, we may then get the fallback if is over five seconds. So what it's doing is over time, if the API is having problems, we gracefully degrade it. That's the second pattern. So let's go back.

The next pattern is a third pattern is retries. So what we've had our timeouts though. We have set the maximum time that you can wait for a response. We've had a graceful degradation. So we've said if we've got an exception inside that timeout, shoot something else, and then pattern three is re:Try. So all about how many times we can re:Try, particularly endpoint to see if it will give us the response that we need. So I've just changed the timeline to be two seconds, not five, otherwise we could be waiting here for a while. And what I'm going to do now is the final re:Try policy. So the re:Try policy is again another policy.

This time, it's the handle is again, gonna be in exception. And on exception, you define what to retry async method is going to look like. So you remember the last one was a fallback async, this one is a re:Try async. So we're gonna set a re:Try count, which is five. And once the re:Try count is set, we're gonna add that policy to our policy wrapper. If you remember it's a combination of all our different policies. So what we're saying here is if the original policy doesn't work, to re:Try that policy, if that doesn't work five times, then hit our fallback policy. So that's what that policy rapper is doing. So let's see what that looks like in an app, so let's re:Start an app.

I don't know, wrap up. And so, let's re:Fresh. Thinking thinking thinking, loading loading loading. So I would tell you UDP joke. You might not just get it. These jokes are great. How many programmers does it take to change light bulb? It's a hardware problem. Tell me another, so far the API is behaving. So, no it's loading. Remember we're hitting that API. If it doesn't respond,

then we're gonna do retries up to five seconds, up to five times. And if that doesn't get back to us, we should then re:Try get our fallback. So here re:Loading again, re:Loading again, re:Trying. Remember the timeout, each request will timeout after five seconds. And here we have fallback. So what's happened, is the API has been hit five times. It's timed out every timeout has been two seconds. So 10 seconds in total. And if that didn't work, we hit at fallback. So that's the re:Try pattern.

So with the re:Try pattern, we can have more granularity over reach retries, no over our timeout. But again, we always have that graceful degradation that fall back in place. The next after re:Try is exponential backoff. So, the next problem that we've got is exponential backoff. We're gonna think about exponential backoff as it's almost, it is exactly. It's not almost, it is improvement over the re:Try pattern.

Why the re:Try pattern? Because if we think about the re:Try pattern, you can define as many retries as you want. So if you're a client and you're hitting this third party API five times, and that seems fine, but just say there is a hundred clients a year. The re:Try pattern in its very basic form is creating a distributed denial of service attack on that third party API. So it's not recommended, but it's indefinitely needed before you can start understanding the more complex patterns, that we're gonna talk about next. The first one of those is the exponential backoff pattern. So if you think about exponential backoff, I've got a little slide for this. So the exponential backoff pattern let's think about it. So the react web app goes to the .NET microservice proxies into the third party app. The third party app, we start re:Trying.

The re:Try does not work. We wait two seconds before we then re:Try. Instead of waiting another two seconds, we actually increase with time exponentially, hence the name. So the next one is four seconds. Then we wait eight seconds. And then finally we wait 16 seconds before we might get response from the third party API. So what that's doing is actually distributing the load into our third party API. So it's a better way of doing re:Try. So let's have a look to see what this looks like.

So, here we are back in our re:Try policy. So explain to the back office, simply changing this re:Try policy and adding that math factor to it. So what we wanna do is apply wait and re:Try async, and then define the mathematics of one of a better word. So what we're gonna do is we're going to ret. We're gonna try three times and then each re:Try attempt, we're going to do over a particular time span.

So that time span, we gonna have a seconds math a power. So we want an exponential. So what we're gonna do is a math power of two, and then re:Try attempt again. So it's gonna give us that two, four it's 16, timeframe that we looked at in the slides. If I just tidy up the re:Try attempt, you can spell, there we go, that you do that. And that is our new re:Try policy to tidy up the code, see of it and see what this looks like. We run the client application and see what the exponential backoff looks like.

So re:Fresh, so I'll just say we're loading. We are calling it. We are every timeout we'll re:Try after two seconds, timeout after two we'll re:Try after four seconds all the way up into 14 seconds. And then if we hit 14 seconds with either a successful request, we will get this. which is the fallback. But as we retry, we should then get the successes as well.

Now let's wait for that. It could be a bit retrying, but waiting for two seconds retrying, waiting for four seconds retrying, then there's one. There's only two hard things in computer science. And then these are werewolves jokes. They're not whenwolves. so what's happened here? We've implemented an exponential backoff.

So what's next? So, there is an issue with retries in denial of service happening, with exponential backoff. There's also something to be aware of. And that is the ability for the retries to cluster as well. So if you think about the way we implemented the exponential backoff, we did a power two math operation before retries. Now, most people will probably end up doing that. And what will happen is the retries themselves will cluster and in effect, they will negate the ability of the exponential backoff to spread the load across the third party API.

So the recommended approach to actually spread that load is by using the jitter pattern. So the jitter pattern is mentioned, if you want to read more about it is in our builders library, which I've got the URL there, and it will go into more detail what the jitter pattern is. But in essence, it's all about spreading that re:Try, that exponential backoff into a more random nature. So I've got some coder on that as well. And well, we can implement that. So let's think about exponential backoff with jitter, which is I'm calling pattern 4a.

So let's just make this a little bit bigger, there we go. So what's this gonna look like? So if we go back into my... we haven't retried async, I need to improve this ad in that randomness. So I do this by adding a time span of millis, and it's a new random, and it's gonna be between zero and a thousand. So zero in a thousand millis. So it's gonna give us a plus or minus one second randomness towards our re:Tries and that's it really. That's all we need to do, because if you think about it, then we're less clustering because it's purely a random re:Try.

So the next one I'm gonna about is circuit breaker. So we went through the whole, what I almost call the three re:Tries. So the re:Tries standard, the re:Try with exponential backoff, and then re:Try exponential backoff and jitter. The next pattern we're gonna talk about is circuit breaker. And I've got a little diagram to explain that as well. So a circuit breaker is where you've got obviously your requests coming through proxy through your microservice, into your third party joke API,

which then the third party joke API has that random injected failure that we have. It will re:Try again 'cause we've done exponential backoff with jitter, It will re;Try after X number of seconds. And then you keep hitting the service is still broken. So all of those re:Tries they're just really useless. So what we can do is completely negate the load on the third party API server by implementing a circuit breaker.

So a circuit breaker, once you implement a circuit breaker, you specify inside that circuit breaker, how many minutes to not push the request through to the third party API. But rather just return a dummy response. So, and then after the minute is over the circuit breaker will go down, and you will be able to then hit the endpoint again. So let's see what that looks like in code.

So I make it bigger. So in this, we were going to add our circuit breaker. So what I'm gonna do, I forgot I didn't stop a bit 'cause it's a little bit messy. So I'm just gonna do a quick refactoring. So what I'm gonna do, because with circuit breaker, you need state. So I'm gonna pull the state up of the policy wrapper in as a class field. So if for the concise, that joke's method is called for every request. So what I wanna do is define my policies and construction of the client. 'Cause it's a single thing rather than at every instantiation so sorry every time it's called. So I'm just defining a class variable called wrapper, and then I'm gonna move all this code here up to be called only when the joke line is constructed.

So that will enable me to well, when he called it once. But also if at any state inside this policy, I can maintain it inside here as well. So I'm gonna call it, in it policies is the method that's gonna contain all of this information. I'm gonna move the actual method call from the joke's method through inside the actual constructor of the joke clients. So that's nice and tidy knowing. So what I need to do is what we're actually here for is to build out that circuit breaker.

The circuit breaker itself, we're going to define as another policy. So first of all, we define the circuit breaker policy and we're also gonna define a circuit breaker fallback. So we can tell that these are when circuit breaker has actually being evoked. So first we do the circuit breaker policy. Again, we have call policy for the circuit breaker. Again, we're gonna handle an exception, for any general error that happens, and then what's gonna happen when the six exception occurs.

We're going to define a circuit breaker. Just tidy this up a bit and dented a bit so you can see it. So the circuit breaker itself, we're gonna say if they call the API five times, in a minute. It's going to break that circuit for one minute. So if you call the API, it has five exceptions, then we're gonna kill. We're gonna implement the circuit breaker for one minute. And then how are we gonna know that our circuit breaker it's in place. Well, we're going to call, we're gonna implement a circuit breaker fallback, and this is what we're denying. So circuit breaker fallback equals policy.

So the handler for this policy, the fallback is obviously like all the other fallbacks. It's gonna return a list of jokes, which is gonna be one joke, but it's gonna handle, and this is a little bit different. We're gonna handle a circuit breaker exception. So it's only gonna be invoked when the circuit breaker fields. So that's right. That, so handle circuit breaker exception, which is called broken circuit. And then once that appears that's then our fallback and inside our fallback again, we're gonna have another anonymous inner function, returns the jokes.

That is our fallback joke. I'll get to think of another joke. This is Connie, good. So this is exactly like the other fallbacks where we have an anonymous inner function that simply returns a list. That list is a single joke. I hope that's over there. I need to tidy that up a bit, dented or go. And that's define the joke.

New joke inside the joke. We need a setup, a string, setup, punchline also string, and then a source. So this will be from our circuit breaker, with single K, thank you.

So another joke, oh, already. So why did the developer go broke? Obviously it's something to do with cache because they used up all their cache!! Just make sure I've got all the arrives, tidy it up a bit, yep. So I find them finally, of course, we add this into our wrapper. So it can cut it in our circuit breaker and our circuit breaker fallback.

Okay, so once that's in, we can see if we can redeploy and run that in our plant up. And hopefully we will get to our circuit breaker fallback and see how the circuit breaker actually works. So we deploy it. We have a couple of seconds, get back into our application and hit the re:Fresh.

Nope, I was very quick. So the API works first time. Of course there we're hitting loading we're retrying, remember we have to re:Try five times before the circuit breaker comes in. So that wasn't five times. Nope, got another. Nope, of course it's always the way when you're trying to task the particular use case.

Nope, this is a bit more, this looks like we're trying to re:Try five times, the exceptions. We need five exceptions and then our circuit breaker is gonna come into force. So that's good. No, oh this is it. Yep, so source circuit breaker fallback. And so now if we evoke the API, we should then get our circuit breaker right away because it's not going to the third API. It's not going to get any sections from that API or re:Try that API. It's just gonna go directly from our circuit breaker. So that's the power of a circuit breaker. And after a minute, of course it will go away and we'll start hitting our API endpoint again.

So that's the circuit breaker, that worked. So there are five practices that we went through today to try and build a resilient app. The last part I'm gonna address today is the practice. So the practice I'm gonna talk about is chaos engineering. So throughout our demos today, I had a third party joke API. And a third party joke API, I've injected some random failures into it so we could see it feeling so we can test and build out our patterns. So that practice is called chaos engineering.

So chaos engineering is not only injecting failures into a service or stressing a service. It's also observing how is that services behaving under that stress and then using that to improve the service. That is inevitably what chaos engineering is all about. It's all about improving the resiliency and performance of your systems by uncovering those hidden issues. Exposing the blind spots or the things you don't know about and a lot more besides.

And why is it really? Why is it difficult? So traditionally you'd have to stitch together scripts and tools to try and bring down services at a particular time, or you have to install agents and complex libraries to get started. Also, it's hard to implement reasonable tests in a reasonable environment. When I say reasonable like production, because injecting chaos into production is probably not what you want to do.

And so that makes it really hard to reproduce "real-world" events. So we come up with last year, the fault injection simulator. So this is a way to inject chaos into your system. So I'm gonna give you a quick demo of how you would use that fault injection simulator with a third party API. So let's say that the third party API we've been using the joke API is running across a suite of EC2 instances. Let's see what we would do to inject chaos using the fault injection simulator. So we'll talk about experiments when we're talking about chaos engineering,

when injected in experiments into a running application. So this experiment, we're gonna stop instances. Now, just to reiterate everything I do here actually stops the instances. It actually works on a real services. So this is not a mock or anything, this will actually happen. So disclaimer there, so we call an action called stop instances, inside that we give it a target and inside the target, we give it some parameters. So we're saying that all of the instances, we're gonna stop them for one minute.

Once we've defined the target, we next need to say if there's any tags. So all of my API servers, EC2 instances are tagged with EC2. Oh sorry, with API. So that way I can be very targeted in what I want to do with this experiment. Once I have defined the experiment, I can create it. And once it's created, you can see that these are my API, so EC2s, and they're all running. I can then run my experiment.

So that I start my experiment, there're lots of warnings 'cause this, as I say, this is real. This is really happening. And the experiment will start to run. So as you can see, the experiment now is pending. The EC2s will run, but if I keep refreshing, refresh should see them stop. So the experiment not running. So there we go. So all the instances are now stopped and they will stop for one minute. 'Cause that's what I define my experiment. So then I can build my application and test my application to see how it's handling the issue of having new servers there.

So as well as stop instances, there's all the actions you can use with the folder injection simulator. If you're using containers, you can control green container instances. You can do a lot of different actions with the fault injection simulator, not just the very simplicity action of stopping at server, which I'm doing. So this is back inside our app. So whether the minute, if we then re:Fresh there we go, our instances are backup. So that's showing us that high targeted default direction, similarly it can be quite granular. You can define time spans that you want the chaos to actually exist in. So if you want to test, this is a production. You might particularly test specific services for specific timeframe at a specific time of day that's cool.

So, that's today's talk. Thanks for staying. So the five patterns I talked to you today were timeouts, graceful degradation, retries, exponential backoffs and circuit breakers. And then the one practice. the quote for today is up on my GitHub repo. If you want to have a look at it, and if you're interested. If you're interested more on chaos engineering, read these articles by Adrian Hornby, a colleague of mine goes into a lot more depth. There's also some free AWS training that you can get here if you want to know more about AWS.

And also please complete the survey, give me feedback on how you find the talk today. That would be really appreciative. And also if you have any particular questions, please tweet me, reach out and yeah, I'll see you next time. Thanks for sticking around, really appreciate it. And I hope you enjoyed the talk. Thanks very much now, yeah.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent