Document Lifecycle Management With Temporal Signals and Timers

Document lifecycle management gets hard once your system must react to thousands of edits, uploads and registrations without wasting resources. You need a solution that scales, stays reliable and is easy to use. Many tools and engines can do this job, and one of our favorites is Temporal.io. Temporal offers ready-made patterns that large products and teams have already tested in production. So developers can apply them quickly and focus on the product itself.

In this post, we show how Temporal workflows can power a framework for document lifecycle management. We use Temporal to handle events from document changes, without loading the system with extra processes or manual steps. Our code samples are in PHP, but you can adapt them to any language Temporal supports. You can find the code for the sample solution here.

The short version: give each document its own long-running Temporal workflow, keyed by the document ID. Your app sends every change to that workflow as a signal, and the workflow queues the events. Then a timer waits for the user to stop editing, and one activity processes the whole batch. When the queue stays empty, the workflow exits and frees its resources.

The Problem: Watching Document Lifecycle Events

Say you have a set of data points, files or documents that something must watch for changes, for example an AI agent or a high-level supervisor. We call this process a “lifecycle.” While the documents sit idle, they create little activity in your system and use no resources. However, everything changes the moment a user edits a file or uploads a new one.

Users also don’t work at predictable intervals. Instead, we expect a burst of activity, followed by a quiet period with nothing to process.

Some of the processes that watch these files can’t run while the user is still working, for example regenerating a summary with an AI agent. So we want to collect some of these changes first, or wait for the user to finish.

The Solution: Document Lifecycle Management With Temporal

Our solution uses Temporal’s ability to create timer-based, event-driven handlers and state machines. With this approach, you can build complex state machines and event observers that resolve dependencies along the way. When the work is done, everything cleans up after itself, so no processes hang and no resources stay in use. Temporal also keeps the handling of each document’s events in order.

We will start with a simple workflow and add functions to it, step by step, until we reach the full solution.

Step 0: Prerequisites

Before we go deeper into the workflow, let’s set up our base abstractions: the event and the event queue.

				
					namespace App\DTO;

class Event
{
   public function __construct(
       public string $entity,
       public string $action,
   ) {
   }
}

namespace App\DTO;

use Temporal\Internal\Marshaller\Meta\MarshalArray;

class Queue implеments \Countable
{
   public function __construct(
       #[MarshalArray(of: Event::class)]
       private array $events = [],
   ) {
   }

   public function merge(Queue $queue): Queue
   {
       $this->events = array_merge($this->events, $queue->events);
       return $this;
   }

   public function count(): int
   {
       return count($this->events);
   }

   // Moves all events to new queue and flushes the current queue
   public function flush(): Queue
   {
       $queue = new Queue($this->events);
       $this->events = [];

       return $queue;
   }
}

				
			

The Temporal SDK can marshal objects and values to carry them between your code, the workflow and its activities. Here, we use the MarshalArray attribute to declare a typed array.

Step 1: Creating the Base Document Workflow

First, create a base workflow with two primary methods: a signal method and a start method. Before we write those, let’s build the workflow base:

				
					namespace App\Workflow;

use App\Activity\ProcessActivity;
use App\DTO\Queue;
use Temporal\Activity\ActivityOptions;
use Temporal\Internal\Workflow\ActivityProxy;
use Temporal\Workflow;

#[Workflow\WorkflowInterface]
class DocumentWorkflow
{
   private ProcessActivity|ActivityProxy $process;
   private Queue $queue;

   public function __construct()
   {
       $this->queue = new Queue();

       $this->process = Workflow::newActivityStub(
           ProcessActivity::class,
           ActivityOptions::new()
               ->withStartToCloseTimeout(5)
               ->withTaskQueue('demo_workflow'),
       );
   }
}

				
			

Signal Method

In Temporal, a signal is a message sent to a running workflow, as the PHP message passing docs explain. Our signal method pushes information into the workflow for later processing in the main loop. It accepts the incoming document events, and the main loop then processes them in order. Here is one way to write it:

				
					#[Workflow\SignalMethod]
public function capture(Queue $events): void
{
   $this->queue = $this->queue->merge($events);
}
				
			

Workflow Start Method

Next, let’s create a simple workflow that calls a single activity when it receives a document creation event. Here is our main loop:

				
					#[Workflow\WorkflowMethod(name: "document.events")]
public function run(string $document_id): \Generator
{
   while (true) {
       // processing our queue
       yield $this->process->handleEvents(
$document_id, 
$this->queue->flush()
 );
      
       // new events might arrive at this point
       if ($this->queue->count() === 0) {
           break;
       }    
   }
}

				
			

We now have a loop that processes events, and the workflow exits once processing is done. If new events arrive during processing, the loop runs again. There is nothing fancy here yet, and there is plenty of room to improve. For example, the current version flushes the queue even when it is empty.

Step 2: Pushing Events to the Workflow

Now that the workflow can receive events, you might ask what such a simple workflow buys you, and why it needs a signal method at all. The trick lies in the code that pushes events to the workflow.

				
					function push(string $document_id, Event ...$event): void
{
   $wf = $this->wfClient->newWorkflowStub(
       class: DocumentWorkflow::class,
       options: WorkflowOptions::new()
           ->withTaskQueue('demo_workflow')
           ->withWorkflowId($document_id)
           ->withWorkflowIdReusePolicy(IdReusePolicy::AllowDuplicate),
   );

   $this->wfClient->startWithSignal(
       workflow: $wf,
       signal: 'capture',
       signalArgs: [new Queue($event)],
       startArgs: [$document_id],
   );
}

				
			

We assume that document_id is a unique file ID and that $this->wfClient is an instance of the Temporal client SDK. If no workflow is running for that document, the call creates one. Then it sends the signal to the new or existing workflow.

You can find the full code of the push helper here.

With this approach, we push events to a workflow queue that starts on demand and closes as soon as the queue is empty.

Document lifecycle management flow: an event trigger reaches Temporal, which creates the workflow or appends events to its queue

The best part of this approach is that Temporal guarantees that events reach the workflow, no matter what. However, only events that arrive while the activity is running join the queue of the same run. Otherwise, the workflow exits, and we have to start it again for every new burst.

Step 3: Introducing Timers

The workflow can now receive and process events, so let’s add timers to handle user behavior better. When you consume user events, timing matters, because users make changes in bursts rather than one event per minute. They work when they are in the mood and stop at other times.

This particular workflow carries no state. In more complex cases, though, loading and updating the document state can be heavy, so you want to avoid frequent workflow restarts.

There are several ways to build this behavior. To start, we will use the simple awaitWithTimeout method.

				
					#[Workflow\WorkflowMethod(name: "document.events")]
public function run(string $document_id): \Generator
{
   while (true) {
       // processing our queue
       yield $this->process->handleEvents(
$document_id, 
$this->queue->flush()
 );
      
       $ok = yield Workflow::awaitWithTimeout(10, fn() => $this->queue->count() !== 0);
       if (!$ok && $this->queue->count() === 0) {
           // workflow is stale
           break;
       }  
   }

   // we are done
}

				
			

We changed the condition inside the workflow, so it now waits for either new events in the queue or the timer. If the timer fires and no events have arrived, the workflow exits. Note that the timer starts again after each batch; we will optimize that below.

As a result, we can collect events for new changes without exiting the workflow right away. The workflow stays alive for 10 seconds after the last user event, but it still flushes the first batch immediately.

Continue-as-New

This solution works well for a short burst of user events. However, when events run into the hundreds or more, a long-lived workflow can fail because its history grows too large. We avoid that by restarting the workflow automatically with continueAsNew when the history reaches its limit. Temporal’s Continue-As-New docs explain how the new run starts with a fresh event history.

				
					#[Workflow\WorkflowMethod(name: "document.events")]
public function run(string $document_id, ?Queue $queue = null): \Generator
{
   if ($queue !== null) {
       // we want to make sure we captured previous and current events
       $this->queue = $queue->merge($this->queue);
   }

   while (true) {
       // processing our queue
       yield $this->process->handleEvents(
$document_id, 
$this->queue->flush()
 );

       $ok = yield Workflow::awaitWithTimeout(10, fn() => $this->queue->count() !== 0);
       if (!$ok && $this->queue->count() === 0) {
           // workflow is stale
           break;
       }  	

       // our workflow is too large, let's continue as new
       if (Workflow::getInfo()->historyLength > 500) {
           break;
       }
   }

   if ($this->queue->count()) {
       // restart as new workflow
       yield Workflow::continueAsNew(
           'document.events',
           [$document_id, $this->queue],
           Workflow\ContinueAsNewOptions::new()
               ->withTaskQueue('demo_workflow'),
       );
   }
}

				
			

Our code now carries the unprocessed queue from one workflow run to the next, and it stops the current run when the history grows past the limit. Once again, Temporal guarantees that the restart loses no incoming events. The result is a durable, time-bound event observer.

The approach looks simple, yet you can also carry the current state of the process between runs. In effect, the document lifecycle can continue for as long as you need.

Document lifecycle loop: queued events go to event handlers, state carries over and Continue-As-New starts a fresh run

Timers, More Timers: Throttling and Deduplication

With a baseline in place, let’s try something more fun. Say your application needs to throttle and batch user events, and also remove duplicates. That sounds like a whiteboard session at first. Inside the Temporal workflow, though, it takes only a modest change.

First, we can handle deduplication at the queue level. Because we keep all buffered events before we process them, we can filter that list. Throttling, which we add later, then gives us more duplicates to catch in each batch.

Add this method to the Queue class:

				
					public function mergeWithoutDuplicates(Queue $queue): Queue
{
   $this->events = array_merge(
       $this->events,
       array_udiff($queue->events, $this->events, fn($a, $b) => $a <=> $b),
   );

   return $this;
}
				
			

We will return to the signal method in a moment. First, let’s create our own timer, called RollingTimer.

This class triggers processing only when the queue reaches the capacity you want or the timer fires. Unlike awaitWithTimeout, this helper tries to reuse the timers it has already created, which saves a few extra events in the workflow history:

				
					namespace App\Helpers;

use App\DTO\Queue;
use React\Promise\Deferred;
use React\Promise\PromiseInterface;
use Temporal\Workflow;

use function React\Promise\resolve;

class RollingTimer
{
    private \DateTimeInterface $last;
    private ?PromiseInterface $timer = null;
    private ?Deferred $ready = null;

    public function __construct(
        readonly private int $waitSeconds,
    ) {
        $this->last = Workflow::now();
    }

    public function touch(): void
    {
        $this->last = Workflow::now();
    }

    public function wait(Queue $queue, int $size): PromiseInterface
    {
        $this->ready ??= new Deferred();
        if ($this->timer === null) {
            $this->timer = Workflow::timer($this->waitSeconds);
            $this->timer->then($this->tick(...)); // unlocks current $this->ready
        }

        return Workflow::await(
            fn() => $queue->count() >= $size,
            $this->ready->promise(),
        )->then($this->reset(...));
    }

    private function tick(): void
    {
        $this->timer = null; // old timer gone

        if ($this->ready === null) {
            return;
        }

        // how long time passed since last event
        $passed = Workflow::now()->getTimestamp() - $this->last->getTimestamp();

        if ($passed < $this->waitSeconds) { // we captured recent event so the pipe is still alive
            $this->timer = Workflow::timer($this->waitSeconds);
            $this->timer->then($this->tick(...));
            return;
        }

        $this->ready->resolve(true);
        $this->ready = null;
    }

    private function reset(): void
    {
        $this->ready?->reject();
        $this->ready = null;
    }
}

				
			

Now update the signal method. Don’t forget to construct RollingTimer in your workflow constructor:

				
					#[Workflow\SignalMethod]
public function capture(Queue $events): void
{
   $this->queue = $this->queue->mergeWithoutDuplicates($events);
   $this->waiter->touch(); // indicating fresh data
}
				
			

Now each new set of data moves forward an internal time mark inside RollingTimer. That tells the timer when the last event happened, so the workflow can wait for the set duration after that event.

The change to the main workflow method is just as simple:

				
					#[Workflow\WorkflowMethod(name: "document.events")]
public function run(string $document_id, ?Queue $queue = null): \Generator
{
   if ($queue !== null) {
       // we want to make sure we captured previous and current events
       $this->queue = $queue->merge($this->queue);
   }

   while (true) {
       // wait for timer or queue to fill up for 8 items
       yield $this->waiter->wait($this->queue, size: 8);

       // no batches to wait for, exiting
       if ($this->queue->count() === 0) {
           break;
       }

       // processing our queue
       yield $this->process->queue($document_id, $this->queue->flush());

       // our workflow is too large, let's continue as new
       if (Workflow::getInfo()->historyLength > 500) {
           break;
       }
   }

   if ($this->queue->count()) {
       // restart as new workflow
       yield Workflow::continueAsNew(
           'document.events',
           [$document_id, $this->queue],
           Workflow\ContinueAsNewOptions::new()
               ->withTaskQueue('demo_workflow'),
       );
   }
}
				
			

You can try this demo in the GitHub repository. It includes two runner files, and one of them can simulate random event activity across many documents.

Building AI Agents with Temporal (Replay 2024)

AI agents that work in production need more than clever prompting. They also need durable execution. In this series, we cover the practical side of building stateful, long-running agents.

Watch the first session below, and explore the full playlist here to see how we use Temporal to handle flaky LLM providers and complex reasoning chains. The sessions also show AI workflows that pick up where they left off when a service fails, without losing a transaction. To see how we apply this for clients, visit our page on AI agents on Temporal.

Conclusion: Document Lifecycle Management in About 200 Lines

Temporal features such as timer-based, event-driven handlers let you build complex workflows that handle user events efficiently. Add a state machine to this workflow, and you get a durable, reliable tool for document lifecycle management in about 200 lines of code.

Spiral Scout is a Temporal partner. For related patterns, read how to pass context between Temporal services, how to trace Temporal workflows in Datadog, or our guide to AI document ingestion.

The production-grade automation blueprint

Stop building fragile chatbots. Get the exact 5-phase blueprint we use to extract your team’s tribal knowledge and install durable, bank-grade AI systems that actually run.

Install the machine.
Stop renting the operator.

We don’t sell hours, headcount, or throwaway POCs. We install the agent-driven systems and automation infrastructure your business needs to scale.

Discuss your infrastructure directly with a senior engineer.

Scroll to top