Event Sourcing Scaling - Pay Less, Do More

Michael Feinstein · Reversim Summit 2018 transcripts · Markdown

Human subtitles from YouTube. Click a time to play the video from that point.

00:12 Hi everyone, good afternoon My name is Misha and for the past year and a half I'm the infrastructure team lead at Trax. Today I wanted to share with you a process we have been going through, led by the infrastructure team designed to improve the efficiency and performance of our system especially in aspects related to extreme load and scale. But before I dive into some technical details, I would like to talk about the infrastructure team and its role in the company. When one says infra team, in Trax as well as in other companies, I suppose that you imagine a set of responsibilities that although might being a bit amorphic it has two essential purposes. The first one is to allow other development teams to develop and deliver their features as fast as possible. In parallel, the second purpose is to achieve some sort of standardization and technological uniformity across the different teams. In companies working in micro-services architecture,

01:12 each team is running its own black box service without being dependent on other teams. This creates a need in an entity that will have a more holistic view on the system and would be able to tell whether those black boxes connect into a system that actually gives value to our company. In Trax, this role is given to the infra team as well. What differs this role from the previous two is that its motives are external to the team. The requirements for this role are not being gathered from within the team and sometimes even not from the R&D department. They are coming from all across the company and based on 3 main concepts: The first one is the requirement for simplicity We always want our system to be as simple and as generic as possible, as robust as possible, we want to be able to extend it and change it easily. This is the basic technological requirement from the infra team.

02:13 Like any other technological requirement, it comes from our CTO who is the leader of the tech domain in our company. In parallel, we have another requirement: meeting the needs of our customers. Each team may say My micro-service is working well, providing quality results without breaching time limits but only the infra team can assure that the whole is not smaller than its parts We should assure we don't have data loss We should assure we don't have down time We should assure we meet the SLA The origin of this requirement is the operations team which are the ones working with the customers The third requirement in this triangle, is a financial requirement. This requirement is becoming more extreme for companies running their systems on the cloud. At the end of each month, we pay our cloud provider either for compute power or for other services we consume

03:14 and it's quite easy to disperse with the payment. We would have liked to reduce this payment as much as possible I suppose you already understand by how this slide goes that the one requesting this, is our CFO. Now, these three requirements sometimes go together it's rare but it happens, however, most of the time they collide and pull to different directions. Basically the infra team is trying to keep this requirements triangle in some sort of optimal situation of "happiness" that will please all sides. In order to explain you how we achieve this at Trax, I'll talk a bit about our business case and the system we developed in order to meet it. Trax was established about 7 years ago, and decided to digitize the world of retail. Trax actually realized that both retailers and manufacturers don't really know what happens on theri shelves in real time. For example, on the following image you can see a shelve with an empty space on it this space is a direct loss to both the retailer and the manufacturer.

04:17 Think about a customer that enters the supermarket looks for a specific product and finds this empty shelf instead of it. The customer has 2 options: Either he goes to a nearby supermarket to but the product, and than the retailer lost the customer Or he decides to pick a different brand causing our manufacturer to loose a customer. Obviously, our manufacturer is interested in a lot more Not only whether its product is on the shelf or not but also where it is located on the shelf. Is it displayed on an eye level convenient shelf? Or is it displayed on a lower shelf that is both hard to notice and to pick from? You can extract many more from this image, things like prices, promotions etc. I'm sure you can think of much more and all this good is taken out of only one single image of a single shelf. Now think that Trax is processing tens of millions of images from all over the world.

05:17 you'll get that rather than those 'single shelf' analysis we provide our customers we can even provide higher level analytics on how you should actually arrange the shelves based all the images we've processed. In order to implement such a system Trax built an event-based, asynchronous backend. This means that each component in our system, each micro-service might register to events that are published to the world and the moment the event has arrived to start its own processing flow. One of the main events we have in our system is the event stating that a new image has arrived. This event is subscribed by a micro-service that recognizes products in the image using sophisticated deep learning algorithms. Notice that this micro-service is totally asynchronous! It doesn't provide any response to the source of the event. There is no other micro-service that is waiting for a response from this service. All that is required from our micro-service is to publish a new event at the end of its work

06:18 stating that the processing task has finished and those are the results of it. This kind of asynchronous, event based micro-services architecture has many pros & cons which I wouldn't cover here as it's a whole separate topic whoever do want to dive deeper into it, I really recommend on a talk given by Martin Fowler about a year ago in Chicago that covers this topic really deeply. however, I do want to mark 2 advantages of the architecture that were really important to us at Trax. The first advantage of systems of this kind is their fault tolerance. Think about an instance of a service that from any reason has crashed. The crash of this instance in this kind of architecture doesn't affect on our system and doesn't brake any flow. The message that was processed by the crashed instance will go back into the messages queue, another instance of the same service will pick it up and start processing it and as no other service was synchronously waiting for a response from the crashing instance no flow is broken and all other services continue to consume events and work as usual.

07:25 The second big advantage of this architecture is that basically, this kind of architecture allows us building much more complicated systems in a relatively easy way in some kind of a Lego based composition where the connecting wires are the events of the system. Basically we get some kind of a data pipeline where on one side we get images as our input, on the other side we provide insights to our customers and in the middle we have a bunch of micro-services communicating through events. Obviously our production system at Trax is much more complicated than showed in this slide and last time I've checked we had about 94 or 95 services in the system but basically that is the system. it's not that difficult to expand the diagram on the slide to 94 services. Another great thing in this architecture is that each one of the services can scale autonomously with no relation to other services. Remember that each one of these services consume different events

08:27 and process those events for different period of time Thus it shouldn't take into consideration other services and can scale due to its own requirements. Now that you understand Trax's architecture we can go back to our requirements triangle and we will try what each one of the vertices (questions later) would say about the system. As I'm an engineer, I would obviously start from analyzing the CTO. So, as far as I'm concerned, the CTO should be quite satisfied from our system. We have built a system, that is pretty simple for its complexity. It is very robust We can easily expand it by adding more services We can change it quiet simply by rerouting events It is generic, it has built in scale Sounds good overall. And now we should ask ourselves whether the COO and the CFO are also satisfied

09:28 And unfortunately, the answer regarding both of them is that they are a bit frustrated So a while ago, the COO came into our R&D infrastructure team room and says: "Listen guys" "Overall our system is doing great, "Our customers are getting their insights and it seems like everything is working well "However, there are times during a week or even during a day "in which we experience peaks in the load "suddenly more customers are uploading images simultaneously "and we are experiencing delays in the system "If we promised a customer that he'll get a report 5 minutes after he took the picture in the supermarket "We find our selves keeping him for 15 minutes until he gets the report" Obviously, this is totally unacceptable. Now, if that wasn't enough for us On the way of the COO out of the room, the CFO is coming in, saying: "Guys, great system, we have tons of customers "we have a great income "but I'm looking at our bill to our cloud provider at the end of the month "And then I'm doing my math, balancing income and outcome

10:30 "and i found out we are not that profitable. You must reduce the expenses" Once they are out of the room we sit down in the infra team and try to figure out what is actually the problem in our system and the problem is that in the holistic view that we are used to examine our system we just can't find out what is the problem. And here I reach a message that somehow relates to the previous talk as well which for me is probably one of the most important messages in my talk and if there is one message i'd be happy if you take away with you it would probably be this one. The message is: Monitoring your system is maybe not the most urgent thing but probably the most important thing you should invest in Now, some of you are looking at me and say "Obviously monitoring is important, unit test are important as well and there are many other important things, you didn't say anything new" and maybe there are some among you that say: "Our cloud provider in monitoring our system with lots of out of the box metrics" PagerDuty as was mentioned before... "we are covered" but when I'm talking about good monitoring, I'm talking about two main concepts

11:30 The first thing is choosing the correct metrics for monitoring. Many times, only you that know the specific business logic of your application Only you, know what are the important metrics that you'd like to monitor. Often, the cloud provider will monitor lots of things and those are important things and you want them to be monitored but in most of the times it wouldn't point the heart of your system. It wouldn't be able catch the really important metric for you. The second important thing is the visualization of the monitoring. Often, even if you monitor the correct metric without a correct presentation of the results you will not be able to understand what is the problem in the system and whether there is one at all. Now that we understand these concepts we can go back to our issue and try to understand what exactly happened. Let's remind ourselves that the COO complained about our scaling mechanism We should actually ask ourselves what is the demand in our system

12:31 What is that defines the scale in our system? I suppose that most of you work with systems, or are familiar with systems that are scaling following their CPU or memory usage those are the standard things. But in event based systems there is one less mediated and more direct datum which can help us to determine the scale. This datum is the queue depth, the number of messages in the queue. And indeed, the cloud provider, out of the box, determines this datum as the one that will influence the scale in event based systems. What is the problem with this datum? The problem is that this datum is reactive Relying on this datum as our scale metric is reactive by its nature. When we have a message that is waiting in a queue, we already lost precious compute time for a message that resides in the queue rather than being processed in our service We can't afford ourselves to scale out when we have messages in the queue and scale in when our queue is already empty.

13:33 Actually what we would like at any given moment is to have some amount of spare compute power that is kept idle without doing anything which are waiting for new messages that arrive into the queue in order to take them for immediate processing. Realizing that we want spare compute power makes us understand something deeper - looking at the queue depth is not telling the entire story. Think about the following scenario: Our queue is empty, but all our workers are currently busy with processing events. In this case, looking only at the queue depth will cause us to scale in, and remove compute power while what was really required, due to the fact we want spare compute power is actually scaling out. It seems like the the correct metric for scaling, is the following one: We would like to sum the number of messages in the queue (which ideally will be zero but sometimes will be positive) plus

14:33 the number of messages that are currently being processed. The sum of these numbers will represent the actual load of messages in our system that should be processed to this we are adding our spares that will allow us to handle new message that might arrive. Now that we seem to have a more reasonable metric we are going back to the second bullet and start to visualize our system monitoring The following graph represents ten working minutes of one of our system services showing the demand for the service in yellow which corresponds to the formula we have reached in our previous slide. In the green line, you can see the supply; the number of compute instances that are actually running at each moment. The presentation itself of both graphs on the same coordinate system clearly shows us both issues that the COO and the CFO were talking about. This entire area, the green area, in which the supply line is topping the demand line

15:34 is actually an area representing money waste in which we hold more compute power than we actually need. Somewhere in the middle of the graph, we have sudden increase in the demand and the entire yellow area is actually an area representing delay for our customers. We have more demand than supply and we are don't stand the load that the customer create for us. Another thing that we may take out of this graph can be found towards its end, here in the red circle. What happens here is that the default scaling mechanism of our cloud provider is reacting Let's put aside that the reaction is not aggressive enough and doesn't scale up enough machines . This could be handled quite easily the real problem is that the reaction is very late. the slowness of the reaction is caused by the fact that the cloud provider measures the queue depth, the number of messages in the queue at most each 5 minutes. Taking that, at the worst case scenario, there are entire 5 minutes in which we harm our customers and do not react to sudden load that arrives.

16:34 So, we already have two main concepts we would like to implement in our solution in order to gain better scaling First, we would like to replace the metric we are based on we realized that queue depth is not enough for us. Secondly, we would like to measure the parameters that compose our metric much more frequently. We would like to measure, for example, once a second both the queue depth and the number of messages in progress and in addition perform our scale operation more frequently as well. And indeed, we implemented these things and developed a new service that measures the parameters once a second and performs the scaling operation. And what is the most important thing that we do when we deploy a new service? Correct, monitor! So we monitored This is how the end of our graph looks when the old scaling is in action based on our cloud provider out of the box mechanism and this is how it looks right after we deploy our service Seems like we solved the issue! Notice, that event when we have a sudden increase in the demand

17:37 the supply is reacting very fast and the yellow line of the demand never crosses the supply line. Effectively we don't harm our customers and react quickly enough. In addition, we keep our supply spares quiet tight to the real demand and effectively don't waste too much money on idle instances that are waiting for new incoming messages. And still we have an issue with this graph which should concern mainly our COO. Notice that since we have deployed the service we see a sudden increase in the demand Increase in the yellow line level Now I remind you that all we have done was to change the scaling mechanism. Changing the scaling mechanism affects the supply! How could it be that changing the scaling mechanism that should impact the supply, affected the demand?! So two things we should address here... First of all, we don't monitor our system well enough.

18:37 Looking at the right side of the graph wouldn't reveal us that we have a problem. That means that the monitoring is problematic. We understand that there is a problem only because we are looking at both graphs simultaneously. The second thing we should address is why the hell the demand increased? Let's try to understand that... Imagine we have 4 compute powers 2 of which are currently dealing with messages and let's assume our system defines we should keep one compute power as our spare. What we would then like to do here is basically scale in and get rid of one compute power As our system is pull based and each of our workers access the queue independently and pops a message we don't have a load balancer that will split the load between the workers and can drain out one of them before we take it down. That means we are in a sort of Russian roulette which will take down one of our workers when we decide to scale in and in the worst case scenario this worker might be currently processing a message Let's put aside the fact that the work we have already invested in this message

19:37 will be thrown away and we will have to reprocess the message from the beginning. What really bothers is that the message of the worker that was taken down will now be returned to the queue and now our demand, instead of reflecting the natural inflow of the system now reflects a sum of the natural inflow of the system plus messages that returning to the queue for the second time and maybe later on will return for the third time, and the fourth and so on. What we would like to do is to implement a mechanism that states that workers that are currently processing messages are locked and do not participate in the scaling game. Luckily, the cloud provider has the option to invoke an API call that locks workers outside the scaling game. We are actually implementing a methodology per which when a worker pops a message from the queue it raises a flag, states that it is gone out of the scaling game and once the message processing is finished it takes the flag down and return itself to the pool of compute powers that participate in the scaling game.

20:37 This assures us that the workers that goes down will be an idle one that doesn't process any message. Basically we've added another concept to our solution This concept states that we should lock workers that process messages outside of the scaling game. Let's take a look at our monitoring graph once we have added this capability So we are looking once again at our famous supply-demand graph and it still acts exactly as expected the supply is staying tight to the demand, the demand is not breaching the supply but we can notice something new it we didn't see before and that's a new red line, that stays always tight to the X axis. This line represents the delay in our system. The red line basically states what is the oldest messages that currently resides in the queue and being pulled to progress The fact that both the supply-demand lines are still performing like previously, together with the fact that the delay line is staying very close to the zero line ensures us that we don't harm our customer,

21:38 we don't breach any SLA we are committed to, and ultimately our COO is now satisfied. So we reached a state in which we satisfied one of the vertices in our triangle; the COO started the journey unsatisfied, and now, at least from this perspective, he is satisfied. But we must ask ourselves "what happened to the CFO?" he was unsatisfied as well at the beginning What you see here is a graph representing our payment for one of our compute power of one of our services in the system to the cloud provider. On your left side, you may see the payment we used to pay for a month in which we used the out of the box scaling mechanism of the cloud provider which is provided by default The middle column represents a month in which we started running our new scaling service And on the right side, just by me, you can see a month in which our new scaling mechanism is fully stable and operational. Seems like we are saving about 70% of the cost! Cool, isn't it? However, some of you might say about this graph is

22:39 that basically it's cool, but, I don't state what was the demand in these months. If the demand was cut-off by 70% it's not such a big deal So the truth is that not only the demand didn't go down by 70% it grew by almost 20% Which means that are CFO should be even more happy as we save probably more than 70% of the cost Cool So we are going back to our requirements triangle and happily mark both the COO and CFO with a green V, we have satisfied both vertices that have started the journey unsatisfied, and it seems like our job is done. However, we must remember that we started the journey with a happy CTO and we must ensure that after inserting such a major technological change, he is still satisfied. So let's recap our solution and try to find out what our CTO thinks of it. We started with a system that looks like this, events are coming in, customers are getting insights and in the middle we have bunch of micro-services, events

23:39 look ok and we'll start from the last part we've added: we have added a mechanism that locks some of the workers outside of the scaling game apparently this shouldn't bother our CTO too much, there isn't anything wrong with that just notice, that when you lock compute power, you are executing it with a timed out operation otherwise, if the following unlock operation fails, you'll get stuck with an instance that will never go down and scale in. OK, so that's one thing and our CTO is still fine with that but we have done more than that, we've added a new service to the system and this service is performing synchronous calls once a second to various resources. It measures the queue depth, the number of messages in progress and then, additionally, performs a scale operation on our system. Here our red alert is already blinking we basically have added a component which is a single point of failure in our system. If this service crashes, for any reason, we don't have scale in our system!

24:39 So, obviously we noticed that and added the simplest solution: We added another one, so we'll have a disaster recovery plan. and indeed, we ave two instances that are working in parallel if one of them crashes, nothing bad should happen. You might ask yourself how it is possible to scale a system in parallel from two different instances So the solution for that is having an absolute scale. The scale should state how many instances we actually need rather than stating relatively that we should increase 3 instances or shut down 2 of them. But still, there is a problem. It is still a new service that we developed in our team and there might be a systematic failure that will cause all of its instances to crash. Obviously we don't want to be left without scale mechanism What we actually would like is to have our cloud provider's out of the box scale mechanism as a fallback. so it will take charge if we crash. And indeed, we didn't replace the cloud provider's out of the box scale we just added another, our own, scaling mechanism to the system.

25:39 As our new mechanism is much more aggressive and much faster than the out of the box scaling mechanism, it doesn't allow it to come into action. The cloud provider always feels that it is satisfied in terms of scale, If, for some reason, our mechanism crashes Automatically, without any further action, the cloud provider's mechanism will understand that it's not satisfied anymore, and will start performing. It's true that we'll have a small bump in our performance, and we might pay a bit more but we already lived with this situation for about 7 years, we can deal with it for one more day until we fix the issue in our service. This entire story might feel imaginary to you but on last Yom Kippur, and that's a real story our scaling service crashed for the first time and indeed, there was no emergency. there was some bump in the performance but the customers didn't even notice it. The scaling mechanism of the cloud provider took control and started handling the system So, finally, we have 4 concepts to our full solution. 1. Use a correct metric for both monitoring and execution

26:41 2. Measure and take actions very frequently 3. Take busy workers outside of the scaling game 4. Always have a robust fallback that you can rely on So now we have finally a situation in which all our 3 vertices are satisfied, Making them happy obviously makes us happy as well. Now we can have our focus on creating presentation for Reversim and you can have your focus on asking questions. Q: Why is a delay of a minute so problematic for you? A: For us at Trax, even the minimal delay to our customers in our system is probably the worse thing. Remember that we have a pipeline of services and each service can suffer from this situation if we had a one minute delay in the first service and then a one minute delay in the second service and in the third one as well, we might have ended up with a 30 minutes delay. This is obviously unaccepted and we agree to pay a bit more in order to prevent it. Q: Seems like there are relations between your services as they are situated in a pipeline.

27:44 Is the work done by the scaling service on one of the services, should influence the next service in row? A: So, yes. Ideally we can implement a system that understands that one of the services scaled out due to load, and we can already start warming up the next service in line. However, as our system react very quickly, we don't have to do so. In addition, remember that each service handles events for different duration. Processing in one service may take 5 seconds and in another it may take 1 hour. Due to this, we don' t know how much in advance and how many instances should be warmed up. It bring some sort of coupling between teams and services that we would like to avoid The scaling service is working on each service independently and tries to ensure that there will be no delays in this specific service. Q: Is there a limit for the number of running instances you define in order to save money? A: Obviously yes. There is a bar we are not willing to cross. This bar was defined by historic overview of our system and the understanding of what is an acceptable load in the system.

28:45 We should always make sure it is still relevant and adapt it to our growing system. But again, obviously the answer is yet. We won't let our scaling service go crazy due to a bug and launch instances forever. Q: Why don't you use Serverless methodology? Why do you use an EC2 like compute power? A: So we thought about it. First of all, Lambda itself has a problem. Our services execute quite complex algorithms there are services (...up to 5 minutes...) there are services that might even run for 1 hour per message for offline tasks we can't run it in a Lambda. what we can do, and that's maybe the next level solution is to convert our services to jobs without execution time limit. Whenever a message arrives, a job is launched executes, and whenever it finishes it goes down. Notice, that there is one important concept we should preserve in this architecture we should make sure that those jobs launch quickly enough

29:46 otherwise, we will still have to maintain a mechanism that will launch jobs in advance Q: Can you explain on how you decide when to lock and when to unlock the instances? A: We have developed an infrastructure that allows our services to lock and unlock themselves. the lock is performed automatically. When the service accesses the queue and pops a message, it locks itself. The lock is not done by the scaling service from outside. Each service is locking itself. Once the service finishes handling the message, it automatically unlocks itself. Q: Can you explain a bit about queue load balancers? A: We don't have load balancers. We are using a pull based architecture. Each instance of a service is accessing the queue independently and pops a message. There is an option to use "long polling" when popping from queues. Basically the service is accessing the queue and doesn't return until it has a message to return with

30:47 Only the moment the service has a message in its hands, it locks itself the entire waiting time, the service is idle and unlocked. That's a good question Q: How do you determine the spare number? Basically we should determine different spares for each service, how do we set the correct number? A: So this number is currently set based on a historic view. The number is based on 2 factors: 1) The time it takes us to launch a compute power 2) What is the the maximal acceleration that we might expect in the incoming inflow of the messages at each time for the specific service. We basically want to make sure that during the launch time we will be able to process all new incoming messages. We analyzed our history, and defined for each service the correct number of spares. The next level might be to convert this into a dynamic process that learns the load behaviour in our system on the fly and adapts automatically the number of spares to each period. This method could save us a bit more money, but cost-effective it wasn't worth it That's it, we are out of time.

← Evolution 3.0 : solve your everyday problems with genetic algorithm · Monitoria - A Monitoring Democracy →