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

Graceful poison pill handling in Scala Akka actors

Akka actors make concurrent work look orderly: each actor owns state and processes one message at a time. Shutdown is where that model meets the outside world, where queued jobs, open subscriptions, downstream writes and waiting callers can all be left unfinished.

In Scala Akka, a poison pill is the conventional final signal for terminating an actor. Its mailbox semantics preserve messages already accepted, but they cannot tell whether another service has finished processing. A graceful design separates draining from termination: stop accepting work, settle what is in progress, then send the poison pill and confirm the stop.

This matters during deployments, incidents and autoscaling events, especially for Australian systems spanning cloud regions and teams in different cities. The pattern below keeps the actor small while making its shutdown contract explicit enough to test, observe and repeat.

Why a poison pill needs a drain phase

PoisonPill is a lifecycle signal rather than ordinary work. When it reaches the head of an actor’s mailbox, Akka can process messages ahead of it and then stops the actor; work sent afterwards has no guaranteed turn. Ordering holds for messages from one sender to one recipient, not globally between producers, so a coordinator cannot assume every producer’s final job precedes the stop signal.

Automatic termination is useful, yet graceful handling needs more than trusting it. The actor may own a file handle, subscription, timer or customer data, while a downstream actor may still process the final payload. A pre-stop phase lets the actor reject new commands and report when its own queue is settled before PoisonPill becomes the final instruction.

Practical fixes and troubleshooting notes in the author archive show why small operational details deserve durable documentation. Record the shutdown order, timeout, fallback and evidence rather than leaving them implicit in a deployment script.

Building the actor shutdown contract

For the classic akka.actor API, use two application messages around the built-in stop signal. Draining becomes a normal command, while resource release belongs in the actor lifecycle hook.

import akka.actor.{Actor, ActorRef}

object WorkerProtocol {
  final case class Work(id: String, payload: String)
  final case class BeginDrain(replyTo: ActorRef)
  final case class DrainComplete(worker: ActorRef)
  final case class Rejected(id: String)
}

final class WorkerActor(
  downstream: ActorRef,
  resource: AutoCloseable
) extends Actor {
  private var accepting = true

  def receive: Receive = {
    case Work(id, payload) if accepting =>
      downstream ! payload

    case Work(id, _) =>
      sender() ! Rejected(id)

    case BeginDrain(replyTo) =>
      accepting = false
      replyTo ! DrainComplete(self)
  }

  override def postStop(): Unit = {
    resource.close()
  }
}

BeginDrain changes the actor’s state without stopping it. Work already ahead of that message can run, while later work receives Rejected. Once the coordinator receives DrainComplete, it sends worker ! PoisonPill. If the downstream operation requires acknowledgement, track its in-flight IDs and withhold DrainComplete until the final acknowledgement arrives.

Keep postStop brief and safe to run. Closing a socket or deleting a temporary file is usually suitable; waiting on a slow service inside the actor can block Akka’s dispatcher. For persistent cleanup, hand the work to another component and record its outcome. Do not make a case PoisonPill branch the only cleanup mechanism, because supervision may stop or restart the actor through another path.

Coordinating a safe stop

A coordinator should drive three phases: quiesce, drain and terminate. It sends BeginDrain, waits for DrainComplete with a bounded timeout, then sends PoisonPill and watches for Terminated. A timeout needs a defined outcome, such as escalating to a forced stop while preserving an audit event; it should not leave the process waiting indefinitely.

The wait must not block an actor’s message thread with Await. Use ask from a coordinating actor, provide a finite timeout and remember that ask creates a temporary actor. Message ordering helps only when the same producer sends both phases; producers for unrelated jobs require their own completion accounting.

Australian deployments often span Brisbane, Sydney and Melbourne. AEST and AEDT daylight-saving changes can make incident timelines misleading, so write lifecycle events in UTC and include an offset in local reports. On a workload hosted in a Sydney or Melbourne cloud region, remove the instance from traffic before stopping its workers; otherwise new requests arrive during the drain and receive predictable rejections.

Supervision, privacy and retries

A poison-pill stop is deliberate and normal, so Akka reports termination to a watcher but does not treat it like an exception for automatic restart. A thrown error follows the parent’s supervision strategy and may restart the actor. Restart-aware cleanup therefore matters: make postStop and preRestart safe, and recreate resources in preStart rather than assuming a stopped instance will return with the same state.

Mailbox payloads can also carry personal information. The Privacy Act 1988 and the Australian Privacy Principles require organisations to limit collection, use, disclosure and retention. Keep identifiers out of logs where practical, avoid logging rejected payloads, and clear actor-held data during shutdown. OAIC guidance reinforces that good data handling depends on lifecycle decisions as much as database configuration.

Retries introduce another edge case: a network timeout does not prove the poison pill was not delivered. Give jobs stable IDs, make completion idempotent and decide whether rejected work returns to the queue or a dead-letter destination. Inspect dead letters after each rollout; a quiet shutdown followed by missing output is still a failed shutdown.

Operational checks for Australian projects

Many developers in Sydney and Melbourne run small home labs in apartments, where an orderly shutdown protects background jobs. A separate maintenance note such as the balcony insulation guide illustrates the same habit: spell out prerequisites, sequence each step and verify the final state, even though its subject is home rather than software.

Shutdown runbook

  • Name the coordinator responsible for sending the drain and stop signals.
  • Set a bounded drain timeout with an explicit escalation outcome.
  • Release subscriptions and temporary resources without blocking the dispatcher.
  • Verify termination and confirm that no new jobs were accepted.

Runtime signals

  • Count accepted, rejected and completed jobs for each actor.
  • Record drain duration and the reason for every termination.
  • Alert on dead letters and repeated actor termination loops.

For teams buying Scala support in the Australian market, put the exact Akka version, current licensing terms and expected stop guarantee into acceptance criteria. Older open-source habits may not match a commercial support arrangement. Include a runbook item that removes traffic before the actor stops and another that confirms termination after the bounded drain.

Mechanism Mailbox and work behaviour Cleanup behaviour Appropriate use
Poison pill Messages ahead can finish; later work has no guaranteed turn postStop runs during deliberate termination Final signal after an explicit drain
context.stop(self) Stops after the current message; queued work may remain postStop must still be idempotent Internal stop without a drain requirement
Exception and restart Supervision may restart the actor after a failure Restart hooks release and recreate resources Recoverable runtime or business failure
Forced termination Little opportunity remains to finish user work External cleanup and reconciliation are required Emergency escalation only

Putting the shutdown flow into practice

Adopt the protocol as a small contract between caller, worker and coordinator. The caller supplies a stable job ID, the worker changes from accepting to draining, and the coordinator owns the timeout and final poison pill. This division keeps shutdown policy outside the actor while leaving the actor responsible for its own state.

Test the path with Akka TestKit and a TestProbe: send work, begin draining, reject a later job, receive DrainComplete, send PoisonPill and observe Terminated. Add a failure case where the drain timeout expires, then run the sequence under realistic load so dispatcher delays do not invalidate the timing assumption.

Implement the drain-and-stop sequence in one service this week, exercise it in staging with real shutdown timing, and publish the verified runbook in The Coding Journal so another Australian team can reuse it with fewer surprises.


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