whoami

Lucas Jenß

cat /etc/motd

The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.

Close-up of white dominoes with black dots standing on green felt surface, shallow depth of field, focused mood

ls -la ~/languages/

total 8
drwxr-xr-x
▶ PHP
▶ Ruby
▶ Scala
▶ C#
▶ JavaScript
▶ Objective-C
▶ Shell Scripting

ls -la ~/toolchain/

total 7
drwxr-xr-x
▶ Typo3
▶ Akka
▶ Capistrano
▶ Git
▶ MAMP
▶ Adobe Illustrator
▶ NSTrackingArea (Cocoa)

uname -a

platforms
drwxr-xr-x
▶ Mac OS X
▶ Unix

Stashing messages to prevent Akka actor races

Akka actors are often described as race-free because each actor processes one message at a time. That protects its internal fields from simultaneous mutation, but it does not prevent logical races. A command can arrive before an asynchronous initialisation result, two senders can interleave work, and a retry can be processed after a timeout. The mailbox serialises events; the application must still define which events are valid in each state.

A stashing pattern closes that gap. The actor enters a loading state, buffers commands that cannot yet be handled, and releases them only after the required dependency is ready. This is more predictable than letting a handler guess, fail, and leave a caller uncertain. It also makes the readiness boundary visible in code and logs rather than hiding it behind timing assumptions.

The pattern suits actors that front databases, payment providers, caches, or other slow services. It is not a substitute for designing idempotent commands or isolating shared mutable state. Combined with explicit transitions and message identifiers, stashing turns a fragile startup window into a controlled queueing mechanism that can be tested without relying on lucky timing.

Why message races survive actor serialisation

Single-threaded execution eliminates simultaneous access within one actor, not ordering problems between actors or external work. Akka preserves message order from a given sender to a given recipient, but messages from different producers have no global order. A future callback can complete after a later command, and ask can race its timeout. If handlers assume the actor is ready merely because they are running, valid-looking work can be processed against invalid state.

Shared conventions are as important here as they are in a home card game. The example of house-game rules illustrates how clear agreements remove ambiguity about legal actions. An actor contract needs the same clarity: which commands may wait, which must be rejected, and what happens after a failed load should be decided before deployment.

Model readiness as explicit state

Start by naming the states rather than beginning with a Boolean. An actor might move from starting to ready or failed, while separate fields track active requests. Keep transition logic inside the actor and make each transition idempotent. Every message should have an allowed source state, an action, and a destination. If two completion messages describe the same transition, the second becomes a harmless duplicate.

Choose whether requests during loading should wait or fail fast. Stashing suits commands whose effects remain meaningful for a bounded period. Authentication requests, administrative cancellations, and queries about current state may require another response. The actor can acknowledge receipt where appropriate, but it should not pretend a command has completed before it can be processed.

Implementing the stash workflow safely

Akka Classic’s Scala API provides the Stash trait for buffering messages until the actor changes behaviour. The important detail is that the buffered command remains associated with its original envelope, allowing the normal handler to reply to the correct sender after the actor becomes ready.

import akka.actor.{Actor, Stash}
import akka.pattern.pipe

sealed trait Command
sealed trait BalanceResult
final case class Loaded(value: BigDecimal) extends BalanceResult
final case class LoadFailed(reason: String) extends BalanceResult

final class BalanceActor(load: () => Future[BalanceResult])
    extends Actor with Stash {

  private var balance = BigDecimal(0)
  private var failure: Option[String] = None

  override def preStart(): Unit = {
    context.become(loading)
    load().pipeTo(self)
  }

  private val loading: Receive = {
    case Loaded(value) =>
      balance = value
      context.unbecome()
      unstashAll()
    case LoadFailed(reason) =>
      failure = Some(reason)
      context.unbecome()
      unstashAll()
    case _: Command =>
      stash()
  }

  def receive: Receive = {
    case command: Command => process(command)
  }
}

Two details are essential. First, asynchronous callbacks should pipe their results to self instead of changing actor fields directly. This returns state mutation to the mailbox’s single-threaded discipline. Second, set the final state before calling unstashAll, then restore the normal receive behaviour. The stash preserves the relative order of buffered messages, but it cannot repair a transition that already used stale data.

Never block the actor with Thread.sleep or by waiting on a future. Blocking prevents every buffered message from progressing and can turn a temporary dependency delay into a supervisor restart. Model a timeout as another message, then let the actor decide whether to retry, reject buffered work, or enter a failed state.

Controlling ordering, timeouts, and duplicates

Stashing is often confused with ordering. It does not promise that a message sent later by one producer will be handled before one sent earlier by another. When order matters, carry a sequence number or operation identifier in the command, record the last accepted value, and ignore stale events. Give retries the same logical identifier so an acknowledgement can be recognised after a network failure.

Australian deployments make these concerns tangible. A team can be spread across Sydney, Melbourne, Brisbane, and Perth: Brisbane normally remains at UTC+10 while Perth uses UTC+8, and Sydney and Melbourne change between AEST and AEDT. Daylight-saving transitions can invalidate wall-clock assumptions, so use monotonic deadlines for request timeouts. Variable latency on NBN fixed-wireless and business connections also makes a hard-coded pause a poor readiness test.

Keep actor failures separate from build failures. When an Android component fails during setup, the CMake shared libraries walkthrough distinguishes NDK linker problems from application logic. The same diagnostic discipline helps determine whether a request failed because its actor was not ready or because the dependency never started.

Testing races without relying on sleep

Use TestKit and a controlled scheduler to exercise transitions rather than inserting delays into tests. Send a command while the actor is loading, complete the future, and assert both the reply and final state. Repeat the scenario with duplicate completion messages, a timeout followed by a late success, and commands from different senders. These tests should prove the intended ordering and confirm that stale events cause no side effects.

Property-based tests can generate command sequences and verify invariants such as a balance never becoming negative, a transfer being applied once, or a failed load never changing business state. The wider coding journal provides practical examples of narrowing software failures through focused reproduction. Keep race tests close to the actor and seed random data so any failure can be replayed.

Comparing state-management strategies

Stashing works best when work can safely wait and should resume in the same actor. A bounded application queue provides explicit capacity and backpressure. ask suits request-response communication between actors, although it introduces a timeout protocol; pipe is cleaner when the producer already knows the destination. A dedicated worker actor moves concurrency into a controlled boundary instead of concealing it.

For Australian cloud workloads, placing latency-sensitive actors near an ap-southeast-2 workload in Sydney may reduce round trips. Public-sector buyers in Canberra may also require the logging and access controls in the ASD Essential Eight, favouring actors that expose explicit, auditable transitions. Neither consideration removes the need to bound buffered work.

Pattern Readiness and ordering Failure handling Best fit
Stash Buffers until an explicit transition Requires a failed-load path Short, bounded waiting periods
Pipe Delivers asynchronous results through the mailbox Late results need identifiers Actor-owned dependencies
Ask Provides request-response semantics Reply and timeout can race Cross-actor requests
Bounded queue Enforces capacity and backpressure Rejects or delays when full High-volume monitored work

A production rollout checklist

Before adopting the pattern, make the following checks part of the actor’s design review:

  • Give every actor explicit lifecycle states and guarded transitions.
  • Pipe asynchronous completions back to the actor instead of mutating state externally.
  • Correlate commands, retries, and completions with stable identifiers.
  • Bound stashed work and expose the buffer depth as an operational metric.
  • Make recovery paths idempotent so duplicate events remain harmless.
  • Test timeout, duplicate, and multi-sender scenarios with TestKit.

Treat the first rollout as an observable experiment. Record stash depth, transition time, rejected commands, and timeout outcomes, then compare them with the previous behaviour. This turns stashing from a code trick into an operational mechanism with measurable failure modes.

Choose one non-critical actor today, document its state transitions, and implement a bounded stash workflow with correlated completions and deterministic tests before deployment.


cat ~/interests.json

KeyValue
editorTerminal-first workflow
osMac OS X / Unix
vcsGit, distributed version control
deployCapistrano, cron automation
graphicsSVG, Adobe Illustrator troubleshooting
networkingIP validation, SSH, VPN

git log --oneline --reverse

2013-10-30

Solving SVG import issues in Adobe Illustrator CS6 and CC

When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.

2013

Solving NDK build issues on OS X

Troubleshooting native development kit compilation problems on Mac OS X.

2013

Programmatically adding PHP generated TypoScript to the backend configuration

Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.

2013

ArgumentError: Could not parse PKey: no start line

Debugging an SSH key parsing error encountered during deployment.

2011-08-04

Validating IP-Addresses in PHP

Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.

2011-07-09

Cocoa: Using NSTrackingArea

A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.


cat ~/contact.txt

github: github.com/x3ro
stackoverflow: x3ro
coderwall: coderwall.com/x3ro
twitter: @x3rames