concept time in category akka

appears as: time, time, times, times, The time
Reactive Applications with Akka .NET

This is an excerpt from Manning's book Reactive Applications with Akka .NET.

Although Akka.NET itself and how it works might be new to many developers, its underlying principles have been in development for decades, in the form of the actor model. As part of the actor model, independent entities, known as actors, are responsible for performing work. You can have multiple different types of actors within a system, and each of these types can have multiple instances running in the system. Every actor runs independently of every other actor in the system, meaning that two running actors can’t directly interfere or interact with each other. Instead, each actor is supplied with a mailbox, which receives messages, and an address, which can be used to receive messages from other actors in the system. An actor sits idle and doesn’t do anything until a new message is received in the actor’s mailbox; at this point, the actor can process the message using its internal behavior. Its behavior is the brain of the actor and defines how it should respond to each message it receives. If an actor receives more than one message, the messages are queued up in the order in which they were received, and the actor processes each message sequentially. Each actor will only process a single message at a time, although multiple actors can process their respective messages at the same time. This allows you to create highly concurrent applications without having to concern yourself with the underlying multithreading infrastructure and code that’s typically required when developing concurrent applications. It’s important to note also that actors are completely isolated, meaning that any internal information or data owned by one actor isn’t accessible by anything other than that actor.

In all of these instances, you need to have systems in place so that you can re-create an actor’s state as and when required. Let’s consider the example of the shopping cart of previous chapters. An actor represents the user’s shopping cart and stores references to items in the actor’s state; you want to ensure that the user continues to see those items in their cart as they move around the website. If your system experiences a failure that crashes the entire application, when it restarts, you want the user to see all their items in their shopping cart. From a business perspective, if a user spent a lot of time browsing the website adding items to their cart and then lost them, their irritation may result in taking their business elsewhere.

With Akka.Persistence, you can use a snapshot store, which stores snapshots of actor state at specific points in time, allowing an actor to replay states from those points. You can see an example of this in figure 11.3. Rather than recovering every event from the beginning of the actor’s lifecycle, the actor can choose the latest snapshot and replay events from that point on.

Figure 11.3. Snapshots allow you to limit the number of events that must be replayed every time a persistent actor needs to recover its internal state.

To store a snapshot in a persistent actor, you call the SaveSnapshot message with whatever you want as the state. In the shopping cart example, you would choose to store your dictionary of items and item counts. But you don’t want to store a snapshot after every event, because there’s no garbage collection of historical snapshots; they accumulate in the database. Instead, you should save a snapshot either after a certain number of events have been emitted or after a certain period of time has elapsed since the last message. In the following example, you keep track of how many messages have been handled since the last stored snapshot, and if a maximum is exceeded, then you persist a new snapshot. In contrast to event persistence, snapshots are persisted asynchronously, so other messages can be processed while snapshots are persisted. This is because snapshots are designed as an optimization technique rather than a primary storage mechanism.

You can therefore consider the internal state to be nothing more than an initial state along with a number of changes in the form of events. Although this might sound relatively obscure, this idea forms the basis for systems that are hundreds of years old. For example, with accounting records, rather than record the total money in the account at a point in time, you instead maintain a log of all the transactions that have taken place against that account. This includes all debits from the account to their destination, and the credits into the account from their origin. This provides vastly improved traceability and auditing capabilities than what you would achieve with the active record approach, in which you have a line representing the amount of money in the account. You can also rebuild the state, in this case representing the total money in the account, by reapplying every event onto the starting state.

This conceptual model isn’t limited to the accounting world, and a number of systems in software development also rely on these ideas: for example, a Git source--control repository. It has an initial state (an empty directory) along with a number of changes to files in that directory. You might add files to the directory as you develop an application, make changes to files to add new functionality, or remove files entirely. Every time you commit a change to the repository, you have a point-in-time snapshot of the state. This model of persisting changes is significantly more lightweight for source-control systems, as you may need to rebuild the state at a snapshot point. Although you could store the whole repository’s contents at each snapshot point, it would rapidly expand to become a huge file.

The active record pattern isn’t limited to source-control technology; you can apply the model to the applications you write. Let’s reconsider the shopping cart example. The shopping cart has an internal state: the items contained in it as a result of the user adding and removing items. By persisting these events, you can rebuild them into the current list of items. Figure 11.2 shows how to represent a shopping cart actor as a process over time during which events are applied to the state, resulting in a new state. As you scan from left to right, you can see how events are applied, starting with an empty shopping cart and then adding a television; then, adding a laptop and removing the television. At each stage along the way, you can see the state of the shopping cart. This provides significantly enhanced observability of system changes, as well as the ability to audit historical changes, if needed. As you have an ordered list of all the changes that exist in your application, you can pass the list to another actor, and as the new actor replays the events, each event will produce a state equal to the original one. When using active record systems, you don’t get this level of historical detail and so can’t correct historical errors as easily, resulting in invalid data.

Reactive Design Patterns

This is an excerpt from Manning's book Reactive Design Patterns.

The resources necessary to store all those emails will be enormous: hundreds of millions of users with gigabytes of emails each will need exabytes[3] of storage capacity. This magnitude of persistent storage will need to be provided by many distributed machines. No single storage device offers so much space, and it would be unwise to store everything in one location. Distribution makes the dataset resilient against local perils like natural disasters; but, more important, it also allows the data to be accessed efficiently from a larger region. For a worldwide user base, the data should be globally distributed as well. It would be preferable to have the emails of a Japanese user stored in or close to Japan (assuming that is where the user logs in from most of the time).

Figure 2.10. At some point, the increase in speed from adding more resources is eaten up by the cost of maintaining coherency within the system. The precise point depends on the parallel program fraction and the time spent on coherency.

We have so far only regarded the behavior of the explicit queue maintained by the manager actor. This actor, however, has only finite computing resources at its disposal, and even the calculations for deciding whether to drop a message have a certain cost. If the incoming rate is higher than the manager actor can decide about, its mailbox will grow: over time, it will eat up the JVM heap and lead to fatal termination through an OutOfMemoryError. This can only be avoided by limiting the implicit queues—the manager’s mailbox, in this case—in addition to the explicit queues.

Listing 16.4. Pulling work according to a specified rate using a token bucket
class CalculatorClient(workSource: ActorRef, calculator: ActorRef,                        ratePerSecond: Long, bucketSize: Int,                        batchSize: Int) extends Actor {   /*    * first part: the token bucket implementation    */   def now() = System.nanoTime()   val nanoSecondsBetweenTokens = 1000000000L / ratePerSecond   var tokenBucket = bucketSize   var lastTokenTime = now()   def refillBucket(time: Long): Unit = {     val accrued = (time - lastTokenTime) * ratePerSecond / 1000000000L #1     if (tokenBucket + accrued >= bucketSize) { #2       tokenBucket = bucketSize       lastTokenTime = time     } else {       tokenBucket += accrued.toInt       lastTokenTime += accrued * nanoSecondsBetweenTokens #3     }   }   def consumeToken(time: Long): Unit = {     // always refill first since we do it upon activity and not scheduled     refillBucket(time)     tokenBucket -= 1   }   /*    * second part: managing the pull pattern’s demand    */   var requested = 0   def request(time: Long): Unit =     if (tokenBucket - requested >= batchSize) {       sendRequest(time, batchSize)     } else if (requested == 0) {       if (tokenBucket > 0) {         sendRequest(time, tokenBucket)       } else {         val timeForNextToken =             lastTokenTime + nanoSecondsBetweenTokens - time         context.system.scheduler.scheduleOnce(timeForNextToken.nanos,             workSource, WorkRequest(self, 1))(context.dispatcher)         requested = 1       }     }   def sendRequest(time: Long, items: Int): Unit = {     workSource ! WorkRequest(self, items)     requested += items   }   request(lastTokenTime) #4   /*    * third part: using the above for rate-regulated message forwarding    */   def receive = {     case job: Job =>       val time = now()       consumeToken(time)       requested -= 1       request(time)       calculator ! job   } } #1 - Calculates new tokens since last time, rounding down #2 - Caps the token token bucketbucket at its maximum size #3 - Only advances the time to the last integer token, to pick up a fractional part next time #4 - Kicks off the process !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":61,\"ch\":20},{\"line\":61,\"ch\":32}]]"} !@%STYLE%@!
Akka in Action

This is an excerpt from Manning's book Akka in Action.

An actor can only communicate with another actor by sending it messages. This takes encapsulation to the next level. In objects we can specify which methods can be publicly called and which state is accessible from the outside. Actors don’t allow any access to internal state, for example, the list of messages in a conversation. Actors can’t share mutable state; they can’t, for instance, point to a shared list of conversation messages and change the conversation in parallel at any point in time.

Let’s first look at what processing streams with akka-stream really means. Figure 13.1 shows how elements are processed one at a time in a processing node. Processing one element at a time is crucial to prevent memory overflow. As is also shown, bounded buffers can be used in some places in the processing chain.

Listing 13.40. Turning an Event into a Metric
val toMetric = Flow[Event].collect { case Event(_, service, _, time, _, Some(tag), Some(metric)) => Metric(service, time, metric, tag) }

Now that you know the basics of defining and materializing a graph, it’s time to look at an example that does more than just copy bytes. We’ll start with the first version of a log processor.

Reactive Web Applications: With Play, Akka, and Reactive Streams

This is an excerpt from Manning's book Reactive Web Applications: With Play, Akka, and Reactive Streams.

Reactive web applications are designed to cope with varying loads. When building web applications, one critical piece of information that should flow into the design is the expected load in terms of requests per second that the application should be able to handle. This varies depending on the application: a meeting room–scheduling application on a company intranet isn’t likely to generate as much interest (or be available to as many users) as a social media site for sharing funny video clips. Often, and especially in the early stages of a project, concerns about performance are dismissed as premature optimization, the attitude being, “We’ll take care of it when we have enough users.” In reality though, if a site gets popular, users won’t gently and slowly visit the site turn by turn, giving developers time to come up with a way to increase capacity. Instead, the site may be featured on a popular news feed such as Hacker News, and suddenly tens of thousands of people will rush to it without warning. (Incidentally, Hacker News regularly features stories about the impact of being featured on Hacker News, sometimes including the amount of the Amazon Web Services bill.) The problem with such bursts in the number of visitors is that they are often unpredictable, and not being able to cope with them may well mean a website will lose one of its few chances to get noticed by the general public.

In the Scala Play API, all of this core information is represented by the play.api.mvc.RequestHeader trait. The RequestHeader is one of the cornerstones of Play, and it’s both used by Play internally and available to us for interpreting and responding to requests. It also plays a central role when it comes to deciding which piece of code will handle a request at routing time.

Read 20 bees from the roster.
Connecting to the hive.
Assembling bees.
Each of 20 bees will fire 500 rounds, 50 at a time.
Stinging URL so it will be cached for the attack.
Organizing the swarm.
Bee 0 is joining the swarm.
...
Bee 13 is firing his machine gun. Bang bang!
...
Bee 7 is out of ammo.
...
Offensive complete.
     Complete requests:        10000
     Requests per second:    739.540000 [#/sec] (mean)
     Time per request:        1352.514700 [ms] (mean)
     50% response time:        817.450000 [ms] (mean)
     90% response time:        2779.350000 [ms] (mean)
Mission Assessment: Target wounded, but operational.
The swarm is awaiting new orders.