<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maxim Alov on Medium]]></title>
        <description><![CDATA[Stories by Maxim Alov on Medium]]></description>
        <link>https://medium.com/@alovmax?source=rss-5be21b295fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HBLUwK7vSkoPyYHjNU9zKA.jpeg</url>
            <title>Stories by Maxim Alov on Medium</title>
            <link>https://medium.com/@alovmax?source=rss-5be21b295fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 06:55:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alovmax/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Running AI Agents on Kubernetes: Trade-offs and Operational Lessons]]></title>
            <link>https://alovmax.medium.com/running-ai-agents-on-kubernetes-trade-offs-and-operational-lessons-956fc399b4d9?source=rss-5be21b295fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/956fc399b4d9</guid>
            <dc:creator><![CDATA[Maxim Alov]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 17:19:37 GMT</pubDate>
            <atom:updated>2026-08-06T17:19:37.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQDo6nR6ZFO_cdQpjaRGGg.png" /></figure><p><em>Previous article: </em><a href="https://medium.com/@alovmax/event-sourcing-for-long-running-ai-workflows-98bd823b1de0"><em>Event sourcing for long-running AI workflows.</em></a></p><p>There’s plenty written about what agents should do and almost nothing about where they should run. Once an agent edits code, runs builds, and opens pull requests instead of answering a function call inside your web server, the runtime question dominates. An agent that takes real actions is infrastructure, and it deserves the same thinking as any other workload: isolation, failure domains, credentials, lifecycle.</p><p>Kubernetes Jobs fit that workload, and one Job per agent session is a sound default.</p><h3>An agent is a batch job that happens to think</h3><p>The runtime profile of an autonomous coding agent is hostile to the “just run it in the app” instinct:</p><ul><li>It’s long-lived (minutes to hours)</li><li>It’s spiky on resources (cloning repos, running compilers and test suites, holding a big model context)</li><li>It’s side-effecting (writing a filesystem, running build tooling, calling external services with credentials)</li><li>It’s untrusted in blast-radius terms (even a well-behaved model runs third-party code the second it does npm install)</li><li>It’s bursty in count (zero one minute, twenty the next when a feature fans out).</li></ul><p>The unit of isolation should equal the unit of work. Each unit needs its own resource budget and failure domain. The system should scale with demand and cost nothing at rest. And each unit should be destroyed (filesystem, processes, all of it) the moment its work ends.</p><h3>Obvious runtimes don’t hold up</h3><p>An in-process worker pool (agents as threads inside the orchestrator) is the simplest to build and the first to fall over: no isolation, one failure domain, so a single agent’s memory spike OOM-kills the process and its neighbors with it.</p><p>A long-lived worker fleet (always-on workers pulling off a queue) isolates workers from each other but makes you pay for idle capacity to absorb bursts. Worse, the unit of isolation (the worker) outlives the unit of work (the task), and that mismatch is the root of a whole category of “why is this task seeing leftovers from the last one” bugs.</p><p>A serverless function gets per-task isolation and scale-to-zero right but gets the envelope wrong: execution-time caps and a constrained filesystem break an hours-long build-running agent on contact.</p><p>Those requirements, almost word for word, are the spec of a Kubernetes Job.</p><h3>One Job per session</h3><p>Launch each agent session as its own Job: an ephemeral pod that starts, does one task, reports its outcome, and gets torn down. The <a href="https://medium.com/@alovmax/why-ai-agents-need-workflows-instead-of-chat-loops-8c849a112a9f">orchestrator launches and watches agents</a>. The control plane and the data plane fail apart from each other.</p><pre>CONTROL PLANE (one long-lived process)        DATA PLANE (ephemeral Jobs)<br><br><br>+----------------+      launch Job       +------------------+<br>|  orchestrator  | --------------------&gt; |  session pod  A  |  clone, run,<br>|                |                       |                  |  report, die<br>|  (event log =  | &lt;----- report ------- |  own fs / limits |<br>|   source of    |        events         +------------------+<br>|   truth)       | --------------------&gt; | session pod  B   |<br>+----------------+                       +------------------+<br>        ^   restart / redeploy                     ^<br>        |   rebuild state from log                 |  pods keep running while<br>        +------------------------------------------+  the orchestrator restarts</pre><p>The orchestrator can crash or redeploy and the running pods keep working; on restart it [orchestrator] rebuilds its view from the event log and reconciles against the live Jobs.</p><p>Agents only <em>report</em> state, but they never share it: a pod reports progress over an HTTP API as events rather than reaching into the orchestrator’s database, keeping the <a href="https://medium.com/@alovmax/event-sourcing-for-long-running-ai-workflows-98bd823b1de0">event log the single source of truth</a> and the wire contract small and versionable (it matters when the two deploy on different schedules).</p><p>Isolation is per task and total: each pod gets its own filesystem, process namespace, and limits, and clones into scratch that dies with it.</p><p>And lifecycle is the platform’s problem: spawn, schedule, run to completion, clean up via a TTL. You don’t write a scheduler or a reaper, but only declare intent.</p><h3>Why not an operator?</h3><p>Why use raw Jobs and not a custom resource with an operator reconciling agent state? An operator earns its keep for long-lived, declaratively-desired things whose drift you keep correcting, like a database. Agent sessions are the opposite: short, imperatively launched, run once, with no steady state to converge toward. A Job already models “run this to completion.”</p><h3>The launcher abstraction earns its keep</h3><p>Put spawn-and-watch behind an interface, with two implementations.</p><pre>interface JobLauncher:<br>    launchSession(taskId, opts) -&gt; jobName<br>    getJobStatus(jobName)       -&gt; running | succeeded | failed<br>    getJobFailureReason(name)   -&gt; &quot;OOMKilled&quot; | &quot;Evicted&quot; | &quot;DeadlineExceeded&quot; | ...<br>    deleteJob(jobName)<br>    # ... list, logs, pod details<br><br>K8sJobLauncher       -&gt; real Jobs, in production<br>LocalProcessLauncher -&gt; child processes, for dev and tests</pre><p>Now the whole orchestration layer is testable without a cluster: scheduling, recovery, concurrency caps, and failure handling run against the local launcher in plain unit tests. Local dev runs the same code path (“launch a session” resolves to “spawn a process”), so prod and dev differ in one swappable piece rather than branches scattered through the engine.</p><p>The seam carries three warnings, because an abstraction that hides Kubernetes can also hide Kubernetes semantics that must not be hidden.</p><p><em>Liveness</em>. A cross-runtime “is this worker alive” check has to use heartbeat freshness or a pod-phase query.</p><p><em>Isolation</em>. The pod implementation clones into a scratch workspace that dies with the pod. Local launcher should have its own sandbox, a detached worktree per session, torn down on exit.</p><p><em>Branch drift inside the spawn path</em>. Two implementations invite an early return: if a cluster is configured, create the Job and return, else fall through to the local path.</p><h3>Lessons that show up later</h3><p><strong>Cold start is the tax on isolation.</strong> A fresh pod has to be scheduled, pull an image, and bootstrap a workspace before the agent thinks its first thought, on the order of tens of seconds. For an hours-long task that’s rounding error; for a ten-second task it’s absurd. Keep images lean and warm them on nodes, but don’t expect zero, and spend the effort only where task duration earns it.</p><p><strong>A failure needs translating.</strong> A failed Job hands you an exit code and a wall of logs - you can act on a <em>reason</em>. Out-of-memory, evicted under node pressure, deadline exceeded, or the agent’s own command exiting non-zero all live in different places (container termination state, pod status, Job events), and collapsing them into one diagnosis turns “some pods are failing” into “raise the memory limit for this task class.” Build that translation early and once, at the launcher boundary. Per-caller mappers drift apart and double-log the same failure.</p><p><strong>Resource limits are a product decision wearing a config value’s clothes.</strong> Too low and real builds get OOM-killed mid-run. There’s no universal number, only a per-task-class number informed by what agents do, so treat limits as tunable policy fed by real failure reasons, rather than a guess you make once.</p><p><strong>Limits also have an inside.</strong> The platform enforces the ceiling, the workload has to perceive it. A tool that sizes its worker pool from the node’s CPU count and its heap from the node’s total memory runs clean on a laptop and dies inside the pod, where the cgroup limit is a fraction of what the node advertises. Reading the limit is its own trap: under some runtimes the pod’s limit sits on a nested cgroup slice and the root reads as unlimited, so a naive probe falls back to node memory and over-commits by an order of magnitude. Walk the cgroup hierarchy leaf to root and take the first finite limit. On a heterogeneous node pool, add a ceiling that doesn’t depend on the reported budget at all, plus a degraded mode that sheds the heaviest work instead of dying. And distrust a single green run - each run lands on a different node.</p><p><strong>Credentials get scoped to the unit of work.</strong> A session should receive only the secrets its task needs (a token scoped to the one repo it touches, the exact environment variables it reads) and never the orchestrator’s whole credential set. The trust model that holds is an explicit per-task allowlist enforced by name. Name-based allowlisting is auditable. An ephemeral pod is a great blast-radius container only if you also shrink what each pod is trusted with.</p><p><strong>Where a credential resolves matters as much as its scope.</strong> The tempting design resolves tokens in the orchestrator and injects them into the Job’s environment, which means the spawning process trusts a different process, on a different pod, to have done its part. When the injection comes up empty, the warning lands in the orchestrator’s log and the session dies later, elsewhere, with an authentication error nobody traces back. Resolve the credential in the process that spawns the agent, from that pod’s own sources, and log the failure there. Don’t fall back to a broader credential to keep the launch alive. Asession that can’t get its scoped token should fail, rather than escalate.</p><p><strong>“Bursty to zero” is a feature that can break by accident.</strong> The economic win is that idle costs nothing, and it’s easy to undo by adding a warm pool “for latency” and then paying for it around the clock. Reach for warm capacity only when measured cold start hurts a latency-sensitive workload, which most long-running agent work isn’t.</p><p><strong>Scale-to-zero fixes idle cost but not one requester flooding the cluster.</strong> Per-task isolation buys nothing for fairness if a single user can launch fifty sessions at once and starve everyone behind them. Concurrency wants a cap per tenant, not only per cluster, enforced at admission: before the Job is created, count that user’s live sessions, and if they’re at the limit, defer the launch. Deferral rather than rejection keeps the cap humane: the over-limit launch waits its turn, instead of erroring back at a user who did nothing wrong.</p><h3>What the Job spec has to get right</h3><p>A session Job is a few fields away from a footgun, and the defaults are wrong for agents. Switch off retries you don’t want, cap the runtime, and clean up after yourself.</p><pre>Job:<br>  backoffLimit: 0  # an agent failure is usually deterministic, don&#39;t blind-retry<br>  activeDeadlineSeconds: &lt;task ceiling&gt;  # a hard wall against a wedged session<br>  ttlSecondsAfterFinished: &lt;short&gt;  # reap the finished Job so they don&#39;t pile up<br>  restartPolicy: Never  # the orchestrator owns retries<br>  resources: { requests + limits per task class }</pre><p>The urge to set a high backoffLimit is wrong here. A crashed build usually fails the same way on a rerun, and a blind in-pod restart hides that from the orchestrator, which owns the real retry decision and the event that records it. Let the pod fail once and report.</p><p>About the recovery after the orchestrator itself restarts, and this is where separating the control plane from the data plane pays off. Because each pod is an independent Job, the pods keep running while the orchestrator is down, and they keep reporting progress to the event log, which lives in the database rather than in the orchestrator’s memory. So when the orchestrator comes back it trusts nothing it held before the crash and rebuilds its picture from two sources it can trust: <a href="https://martinfowler.com/eaaDev/EventSourcing.html">the event log</a>, which names every workflow that was in flight, and the cluster, which it asks for the Jobs still alive under its label. Then it lines the two up. If a session’s Job finished during the downtime, its completion is already sitting in the log, so the orchestrator just carries that workflow forward. If the log expected a session to be running but no matching Job is alive and no completion was ever recorded, the orchestrator marks that session failed and lets its normal retry policy take over.</p><pre>on orchestrator boot:<br>    live = list_jobs(label = &quot;managed-by=orchestrator&quot;)<br>    for wf in workflows_in_flight(event_log):<br>        for session in wf.expected_sessions:<br>            if session not in live and not has_terminal_event(session):<br>                append(SessionFailed{session, &quot;no live job on recovery&quot;})</pre><p>That reconcile loop is the whole reason the orchestrator can redeploy without disturbing the data plane. The pods kept working, the orchestrator catches back up.</p><h3>The deciding question</h3><p>Running agents as one Job per session is the operational side of a <a href="https://medium.com/@alovmax/why-ai-agents-need-workflows-instead-of-chat-loops-8c849a112a9f">single architectural idea</a>: the engine orchestrates, the steps execute, and the two should fail, scale, and deploy on their own. Jobs give you per-task isolation, independent budgets, a failure domain no bigger than one task, scale-to-zero economics, and a platform-managed lifecycle, which is the profile a long-lived, spiky, side-effecting, bursty agent workload asks for.</p><p>The costs are as concrete: cold start rules out short tasks, failure diagnosis needs a translation layer, limits are a standing tuning problem, and an abstraction over the runtime still has to respect each runtime’s true semantics. So the deciding question is short. Is the task long enough that tens of seconds of isolation overhead is noise? If yes, one Job per session is hard to beat. If no, you’re in serverless or in-process territory, and Kubernetes Jobs are the wrong tool worn with confidence.</p><p><em>Part of a series on building production agent systems. References: Kubernetes Jobs and the TTL-after-finished controller (kubernetes.io). The event-sourced recovery these failure domains lean on is covered separately.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=956fc399b4d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Sourcing for Long-Running AI Workflows]]></title>
            <link>https://alovmax.medium.com/event-sourcing-for-long-running-ai-workflows-98bd823b1de0?source=rss-5be21b295fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/98bd823b1de0</guid>
            <dc:creator><![CDATA[Maxim Alov]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 07:23:32 GMT</pubDate>
            <atom:updated>2026-08-06T16:32:39.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BORBu1OBvtOgLbmPyJ6b7w.png" /><figcaption>Each new fact lands to the right. Nothing behind it gets rewritten.</figcaption></figure><p>Previous article: <a href="https://medium.com/@alovmax/why-ai-agents-need-workflows-instead-of-chat-loops-8c849a112a9f">Building agentic workflows.</a></p><p>Give an agent a task that runs for hours, breaking a feature into sub-tasks and driving each one to a merged pull request, and watch what fails first. It is the state that breaks. The process dies and you have no idea how far it got. Someone asks why the agent did what it did, and the answer got overwritten an hour ago. You restart the run and it redoes finished work, or fires a second irreversible action because nothing remembered the first one.</p><p>It’s the durability and audit problem long-running systems have been facing with for decades. Agents change the texture: the steps are slow, they cost real money, some can’t be undone, and half of them touch the world. <a href="https://martinfowler.com/eaaDev/EventSourcing.html">Event sourcing</a> fits that texture, and the parts worth knowing are the ones a crash drags into daylight.</p><h3>A status column throws away what you need</h3><p>The pattern is to have a mutable row: a status field walks from pending to running to done, rewritten in place. That one decision, overwrite on every update, costs you everything an hours-long run needs. The row says running, but running where, on which step? Whatever you needed to resume got clobbered by the write that set running. A failed value records the ending and erases the path to it, and you can&#39;t replay a run you never wrote down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jb36hcIMaglJYmTsbnG4Vg.png" /><figcaption>Overwrite and you keep one value. Append and you keep the run.</figcaption></figure><p>Instead, one can invert the model. Append facts instead of overwriting them, and derive the current state from the history:</p><p>❌ Don’t</p><pre>MUTABLE ROW (one cell, rewritten in place - history is gone)<br>  workflow_42 | status = running   &lt;- was scheduled, was pending (lost)</pre><p>✅ Do</p><pre>EVENT LOG (append-only facts - history is the data)<br>  seq 1  WorkflowStarted    {feature: 42}<br>  seq 2  StepScheduled      {step: decompose}<br>  seq 3  StepCompleted      {step: decompose, out: 5 tasks}<br>  seq 4  StepScheduled      {step: implement, task: 3}<br>  seq 5  StepFailed         {step: implement, task: 3, err: ...}<br>                |<br>                v   <br>       project(events)  -&gt;  { running, on step 4, 1 failure }</pre><p>Current state is a fold over the log. Nothing is lost because nothing is overwritten. <a href="https://martinfowler.com/eaaDev/EventSourcing.html">Fowler’s “Event Sourcing”</a> is the classic introduction, the pattern is decades older than the AI use case.</p><p>You can own the event model yourself, or adopt a durable-execution engine, <a href="https://temporal.io/">Temporal</a> and <a href="https://caedence.io/">Cadence</a> before it, which records each step’s result and replays your workflow code after a crash, skipping the steps that finished. That’s the same pattern wearing a programming model. Either way, the costs below land on you.</p><h3>The log lies about the world</h3><p>The log records what you meant to do, but the reality could be much more complicated. Your store says you spawned a worker, whether that worker is alive right now, the log can’t say. Recovery is therefore event sourcing plus reconciliation: poke reality, write corrective events. The poke has a trap. Checking a process ID is right for a local child and worthless for an isolated worker whose PID lives in another namespace. The signal that survives every runtime is a heartbeat the worker writes as events: no heartbeat inside the window means dead.</p><p>❌ Don’t</p><pre>on recovery:<br>  for each worker the log believes is running:<br>      # WRONG in an isolated runtime - pid namespaces differ, pids get reused<br>      if not host_pid_exists(worker.pid): mark_orphaned(worker)</pre><p>✅ Do</p><pre># RIGHT - liveness is itself derived from events<br>if now() - worker.last_heartbeat &gt; STALENESS_WINDOW:<br>    append(SessionFailed{worker, reason: &quot;no heartbeat - orphaned&quot;})<br>    <br>    for each timer whose deadline passed while we were down:<br>        schedule_to_fire(timer)</pre><p>Durable timers hide a cousin of this bug. A scheduler that claims a timer, flipping fired to true before running the callback, strands the work if the dispatch after the claim fails: the timer looks fired, the action never ran, and recovery scans unclaimed timers only. Claims need a release path on dispatch failure.</p><h3>Strict inside, lenient at the edge, absolute at the exit</h3><p>Transitions you perform yourself, the workflow and activity moves made in-process, should be strict: an illegal transition is a bug, you should throw in such case. Transitions reported by a remote worker over a lossy channel should be lenient: log the anomaly and apply it, because the “illegal” report is usually a true fact that arrived without its predecessor.</p><p>Leniency stops at the terminal boundary. Once an aggregate is completed, merged, or cancelled, a late event trying to move it back to a running state should be dropped, rather than applied. Otherwise a straggler report resurrects a dead worker, and nothing living will ever report on it again to fix the record. Define terminal-ness once, in one predicate shared by projections, guards, and recovery; a recovery sweep with its own hand-written list of terminal events will miss one and resurrect every run that ended with it.</p><p>One particular race deserves its own rule. A watchdog can see the job finish and mark the worker completed before the worker’s own final report arrives. By the time that report lands, the worker is already terminal, and the guard rejects it as a late transition. Dropping the duplicate status is correct, dropping the whole report is not, because the report also carries the domain event downstream consumers wait on. In that case, deduplicate the state transition, let the rest of the report flow through to idempotent handlers, and never make a consumer wait for an event the terminal guard is allowed to prevent.</p><h3>Not in the log means not after replay</h3><p>The hardest bug to catch: a consumer needs a field, and that field never got written into the event meant to carry it. Everything works in testing, because the value still sits in memory. Then the process restarts, state rebuilds from the log alone, and the field is gone, on the recovered path only, the worst place to find it. Every field a consumer needs after recovery has to live in the event. A schema-driven round-trip test, write then read back, asserting every field survives, is cheap insurance.</p><h3>Snapshots and old events</h3><p>Replay grows with history, so above some threshold you persist the projected state with the sequence it covers, then fold only what came after. A snapshot is a cached derived value, and a corrupt or outdated one hands you wrong state silently. Treat it as throwaway: validate on read, delete on doubt, replay from scratch. Key it by the projector’s version too, or a change to the fold serves stale state from a cache keyed only on data. “Wiping every snapshot is always safe” is the test that you got this right.</p><p>Old events never go away. They’re immutable and they outlive every refactor, so projection code has to read every shape it ever wrote, versioned events and tolerant readers, or a crash six months out ambushes you with a shape you forgot.</p><h3>The append path</h3><p>Two writers can race on one aggregate, and “read the last sequence, write sequence plus one” drops an event under load. The fix is optimistic concurrency: the writer declares the version it believes the stream is at, and a unique index bounces the write if it’s stale.</p><pre>append(aggregate_id, expected_version, new_events):<br>    # a unique index on (aggregate_id, sequence) does the enforcing<br>    next = expected_version + 1<br>    for e in new_events:<br>        insert_event(aggregate_id, sequence = next, payload = e)  # fails on conflict<br>        next += 1<br>    notify(aggregate_id)  # wake the projector / scheduler<br># on a unique-violation: re-read the stream, rebuild state, decide again, retry</pre><p>Keep events small and flat, one fact each, and keep derived state out of them. Derived state belongs in the projection, where you can change the computation without rewriting history. Keep the fold pure. A projection that touches the clock or the network during replay won’t reproduce, and reproducibility was the point.</p><h3>When it’s worth it</h3><p>A mutable row is fine for short, one-shot work. Reach for event sourcing when a run outlives its process, takes actions someone is accountable for, and has to survive a crash without losing or duplicating work, which is the agent-orchestration regime almost exactly. A durable-execution engine hands you the same guarantees behind a friendlier API, but the problems are identical: reconcile the log against a world that never reads it, choose enforcement per aggregate on purpose, keep projections complete, and trust no snapshot you can’t rebuild. Get those right and a crashed six-hour run stops being a disaster. The engine reads its history, lands where it was, and carries on.</p><p><em>Part of a series on building production agent systems. References: Martin Fowler, “Event Sourcing” and “CQRS”; Kleppmann, “Designing Data-Intensive Applications”; the Saga pattern (Garcia-Molina and Salem, 1987); Temporal and its Cadence lineage.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98bd823b1de0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Agentic Workflows]]></title>
            <link>https://alovmax.medium.com/why-ai-agents-need-workflows-instead-of-chat-loops-8c849a112a9f?source=rss-5be21b295fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c849a112a9f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[ai-orchestration]]></category>
            <dc:creator><![CDATA[Maxim Alov]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 17:22:25 GMT</pubDate>
            <atom:updated>2026-07-12T05:49:38.648Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRS65Lg3CxMXcFTUnrNR5A.png" /><figcaption>A workflow of agent steps — a pipeline of the building blocks</figcaption></figure><p><em>This is the first article in a series on building production agent systems: what it takes to run AI as infrastructure, beyond prompt engineering, writing skills, and the patterns everyone already knows. Keeping a system running for hours, through crashes and actions that reach out and touch the real world, is the harder problem this series takes on.</em></p><h3>Introduction</h3><p>A language model should never be responsible for keeping your system up. It’s brilliant at choosing the next move over a focused context. It’s hopeless as a scheduler, a transaction manager, or a recovery system, because none of those were ever its job. The standard agent pattern asks it to be all four at once. That is why demos impress and shipped systems stall.</p><p>That standard pattern is a loop. Hand a model a goal and some tools, let it think, act, observe, and think again until it calls the task done. This is the <a href="https://www.promptingguide.ai/techniques/react">ReAct pattern</a>, and it works for what it’s built for. But it’s doing two jobs at once. It’s the reasoning substrate and it’s the control flow, and those two want opposite things from you. So pull them apart. Let the model reason inside a step, and let an explicit workflow run the control flow between steps.</p><h3>Where one big loop hits the wall</h3><p>Take a task with some shape to it. Turn a feature request into sub-tasks, build each one in the right component, open a pull request per change, wait for CI, answer the review, merge. Run all of that as a single chat loop, one context holding the whole job and deciding every move, and you walk straight into a wall built from a few separate failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8AHXuinHwWS0n7W4JWsmA.png" /><figcaption>A better prompt doesn’t touch architecture</figcaption></figure><p>Context erodes. Everything the loop has ever done piles into one window, and long contexts get worse, not better. Models attend least well to the middle of a long input, so step 40, buried under 39 earlier tool dumps, lands softer than step 1. The loop gets dumber as the task gets longer, which is backwards. There’s no durability. The loop’s state is the context window, the window lives in a process, and over hours that process dies and takes the state with it. You can’t resume, only restart. Errors compound. Each step feeds the next, so a small slip in step 3 gets amplified through step 40, and there’s no fixed plan to snap back to, just the loop’s running improvisation. Chain five steps that are each 95% reliable and you’re at 0.95⁵ (roughly 77%), and the misses cluster in exactly the long tasks you most wanted to hand off. And there’s nowhere to stand. You can’t drop in a human approval, fan work across parallel workers, retry one failed step without redoing the rest, or audit what the plan was and where it drifted. The loop has no seams.</p><p>A smarter model erodes context slower and compounds error less. It still loses everything on a crash, and it still gives you no seam for a gate. These are architecture problems, and a better prompt doesn’t touch architecture.</p><h3>Workflows and agents aren’t rivals</h3><p>Anthropic’s “Building Effective Agents” draws the line well. Workflows orchestrate model steps through predefined code paths; agents let the model steer its own process. Don’t pick a side, nest them. The design that holds up is a workflow of agent steps.</p><pre>CHAT LOOP - one context, dynamic control flow, no seams<br><br>   +-----------------------------------------------+<br>   |  model: think -&gt; act -&gt; observe -&gt; think ...  |  &lt;- all state in here<br>   +-----------------------------------------------+     dies on crash<br><br><br><br>WORKFLOW OF AGENT STEPS - engine owns control flow, each node is a bounded agent<br><br>           decompose<br>               |<br>        +------+------+           engine decides order, parallelism,<br>        v             v           retries, gates, recovery<br>   implement A   implement B   &lt;- run in parallel<br>        |             |<br>        +------+------+<br>               v<br>            open PRs --&gt; [ human gate ] --&gt; merge<br>               |<br>            each node = fresh focused context, typed in, typed out</pre><p>The graph drives what runs next. Each node is one bounded agent task with a fresh context, an explicit input, and a declared output. The model’s intelligence lives inside the node, where it belongs; the reliability lives between the nodes. A node stays small and contract-shaped, and that shape is why the engine, not the model, can own the hard parts.</p><pre>node &quot;implement_task&quot;:<br>    input:  TaskSpec  # typed, not a slice of transcript<br>    body:   run a bounded agent (it may loop internally, in its own context)<br>    output: emit StepCompleted{ pr_url } | StepFailed{ reason }<br>    # the engine decides what fires next, what retries, what runs in parallel,<br>    # and what to record so a crash is recoverable</pre><h3>What you get for moving control flow out of the model</h3><p>Each node starts with only its input, so step 40 is as sharp as step 1. It’s a fresh bounded context, and handoffs carry structured data rather than a growing transcript. The engine records each step’s completion as a durable fact, so a crash resumes from the frontier instead of starting over. This is where event sourcing comes in; the workflow layer is the natural producer of those events, and the explicit control flow is what makes recovery possible at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UBLAGVhPzSNs7qJ-fyx_w.png" /><figcaption>Bounded steps — durable facts — explicit control flow</figcaption></figure><p>“Do these five in parallel, then merge” becomes a primitive with a real concurrency cap and backpressure, something the engine enforces rather than something you hope the model juggles in one head. A failed step retries under its own policy, attempts and backoff and a ceiling, without unwinding the rest, so one flaky external call no longer poisons six hours of work. A gate is a node that pauses the graph until a human answers; a verifier is the same trick, a node that runs after a producer and can bounce its output back. Drop either one in anywhere, because the graph is explicit rather than improvised.</p><h3>What structure costs</h3><p>A graph is more rigid than a loop, and pretending otherwise is how you end up resenting it. You give up some emergent flexibility. If the task really needs the model to invent control flow nobody anticipated, a fixed graph fights you, so push the dynamism down. Let nodes loop internally while the structure between them stays put. You pay up front, too. A scheduler, a state model, retry policy, recovery, that’s real infrastructure, and for a weekend project the loop ships faster. The bill turns positive the moment a job runs for hours, forks across workers, or has to answer for itself later, and after that the engine earns its keep every run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ic35Nmj5o9QEQO-NNgYatA.png" /><figcaption>One question — would you retry these two steps separately — decides whether two steps are one node or two</figcaption></figure><p>You can also over-decompose. Splitting “write the function” from “write its unit test” is usually wrong; they share tight context, pass or fail together, and gain nothing from separate retries. Splitting “build it in service A” from “build it in service B” is usually right; different repos, independent failure, worth running and retrying alone. The grain test is one question: <em>would you ever retry or gate these two steps separately</em>? If never, they’re one node. And the handoff contract, the structured data flowing between nodes, is now a thing you design and version. More work, and it’s what makes the system inspectable.</p><h3>How the engine drives</h3><p>People underestimate the scheduler, and it’s smaller than you’d guess. The engine doesn’t need to be clever. It needs to be a loop that, on every wake-up, asks one thing for each workflow, which nodes are runnable right now. A node is runnable when all its dependencies have a completion event and it doesn’t already have one of its own. That’s the whole frontier computation.</p><pre>tick(workflow):<br>    done = { e.node for e in events(workflow) if e.type == &quot;StepCompleted&quot; }<br>    for node in workflow.dag:<br>        if node.id in done: continue<br>        if any(dep not in done for dep in node.deps): continue<br>        if has_inflight(node): continue  # already scheduled, don&#39;t double-fire<br>        schedule(node)  # emit StepScheduled, launch the agent</pre><p>Because that frontier is computed from events and not from memory, recovery comes free. After a crash the engine replays the log, recomputes which nodes are done, and resumes the same frontier. Retries live one level down. A node that fails emits a StepFailed with an attempt count, and the engine reschedules it after a backoff until the count hits the node’s ceiling, then gives up and lets the failure propagate to its dependents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENpY_frPoAtm1LbLuBWwlg.png" /><figcaption>the tick loop — the frontier — the split</figcaption></figure><p>Concurrency is a cap on how many schedule calls are in flight at once, the rest queued, which is what stops a hundred-node fan-out from launching a hundred pods at the same instant. The has_inflight check is what makes a mid-flight crash safe to recover from. The engine records a StepScheduled event before it launches anything and reads it back on replay, so a node that was already launched when the process died doesn&#39;t get fired a second time on the way back up.</p><p>Pin the handoff contract down early. Make each node’s output a small typed record, validated before it’s written as the completion event, so a node that returns garbage fails at its own boundary instead of poisoning the one downstream.</p><h3>The split that matters</h3><p>The model’s job is judgment; the engine’s job is durability. A chat loop forces one component to do both and does the second one badly, because language models aren’t schedulers or recovery systems. Give the model the focused-reasoning job and nothing else, inside a bounded step. Put the unglamorous, load-bearing concerns, what runs next, what runs in parallel, what to retry, what to record, where to pause, into a workflow you can test, inspect, and recover.</p><p>Use a loop when the task is short, self-contained, and disposable; “investigate this and answer a question” is a perfect loop. Use a workflow of agent steps when it’s long, wide, gated, or auditable. Most things people depend on are the second kind, which is why “agent,” in practice, so often turns out to mean “a workflow with good steps.” The intelligence stopped being the hard part a while ago. The scaffolding that lets it run for hours and be trusted is what’s left.</p><p><em>Part of a series on building production agent systems. References: </em><a href="https://arxiv.org/abs/2210.03629"><em>Yao et al., “ReAct” (2022)</em></a><em>; </em><a href="https://arxiv.org/abs/2307.03172"><em>Liu et al., “Lost in the Middle” (2023)</em></a><em>; </em><a href="https://www.anthropic.com/engineering/building-effective-agents"><em>Anthropic, “Building Effective Agents” (2024)</em></a><em>. The durability backbone here is event sourcing, covered separately.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c849a112a9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Android Architecture 2021]]></title>
            <link>https://alovmax.medium.com/scalable-android-architecture-2021-92208e95c0ad?source=rss-5be21b295fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/92208e95c0ad</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[modularization]]></category>
            <dc:creator><![CDATA[Maxim Alov]]></dc:creator>
            <pubDate>Sun, 27 Jun 2021 06:45:41 GMT</pubDate>
            <atom:updated>2021-06-29T18:55:21.462Z</atom:updated>
            <content:encoded><![CDATA[<p>The subject of Android app architecture has quite a long story. Started from web-inspired MVC, then acquired a shape of a better fit for mobile (MVP), went through more opinionated approaches (Mortar and Flow) to something unshakable and better structured (Clean, MVVM), sometimes branching out (Data Manager) or switching paradigms (MVI). With the release of Jetpack in 2017, Android app architecture has started to standardize and receive official maintenance in terms of programming tools and community support. In this article, I propose the way one can build a modern and scalable Android app architecture with modularization in mind and the help of Jetpack. In Kotlin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hAKzy24e3WoiYaoW4l9w3g.jpeg" /><figcaption>Photo by Bryan Liaw</figcaption></figure><h4>Thesis</h4><p>The Architecture is backed by the principles of Clean Arch: layered structure, unidirectional data flow, independent data models and mapping across the boundary. The presentation layer is organized according to MVVM utilizing Jetpack extensively. The project is split into product features and core libraries (network, analytics, etc.). Each, in turn, follows a conventional structure to reach better isolation, a clear dependency graph, and a high modularization, which is good for parallel development, debugging, and build performance.</p><p>Another quite important principle that is also baked into the concept is <em>reusability</em>. Public entities are clearly defined and yet highly accessible making it possible for one feature to reuse the functionality of another. And this is all done in a type-safe and compile-time safe manner.</p><p>Before we dive into details, it’s important to note, that the Architecture is based on DI principle, and the best tool to build scalable Android app architecture is Dagger 2. So, that library (better say “a framework”) is ubiquitous in this article. Please, make sure you are familiar with it.</p><p>The Architecture also supports both classic android-library modules and android-dynamic-feature modules in a natural way.</p><h4>Big Picture</h4><p>Let’s give a definition: there are <em>product features </em>(such as <em>authorization</em>, <em>feed</em>, <em>profile</em>, <em>cart</em>, <em>details</em>, etc.) and <em>core libraries</em> (such as <em>network</em>, <em>analytics</em>, <em>feature flags,</em> etc.). There is also a bunch of <em>utilities</em>, but we won’t stay put on it. In general, there is no big difference between these two, they look similar, but it’s convenient to have this difference along. I will use term <em>feature</em> for both <em>product feature</em> and <em>core library</em> where the difference doesn’t matter, and concrete definition where it actually does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_oU00ExywtppvzRU6L_vw.png" /></figure><p>Let’s imagine we are building an Android application to display a list of stocks. It could look like that (full source code is <a href="https://github.com/orcchg/SampleAndroidArchAtScale">available on Github</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZ1KjUnDzbi8MbZQCcT7oA.png" /></figure><p>The project structure could look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*js1yC71YW_PZipM4JUvJ1g.png" /></figure><p>So we’d have a <em>product feature</em> called <strong>:stock_list</strong>.</p><p>By convention, <em>product feature</em> has the following module structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*7k6c9jiBUgsK-BUYB-UcPQ.png" /></figure><p>This can be illustrated the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRV0gRyP9-vS0v0v0YHyog.png" /></figure><p>Here each module is a <em>Gradle module</em>. The roles are following:</p><ul><li><strong>api</strong> - defines a public interface for a feature. The module contains <em>domain models</em>, <em>FeatureInteractor</em> interface and <em>FeatureApi</em> interface. For a <em>core library,</em> we would say <em>CoreLibInteractor</em> and <em>CoreLibApi</em>.</li><li><strong>impl</strong> - defines an implementation for <em>FeatureInteractor</em> from <strong>:api</strong>.</li><li><strong>fake</strong> - defines a <em>fake</em> implementation for <em>FeatureInteractor</em> from <strong>:api</strong>.</li><li><strong>data:api</strong> - defines an interface of the <em>data layer</em> of the feature. The module contains <em>FeatureRepository</em> interfaces (one or many depending on implementation details and separation of concerns) and <em>FeatureDataApi</em> interface.</li><li><strong>data:real</strong> - defines an implementation for <em>FeatureRepositories</em> from <strong>:data:api</strong>. There could be many <strong>:data:real </strong>modules (with different names), for example - if one needs to have the same data from different backends.</li><li><strong>data:fake</strong> - defines a <em>fake</em> implementation for <em>FeatureRepositories</em> from <strong>:data:api</strong> (actually, no need to have multiple fakes).</li><li><strong>data:wiring</strong> - wires <strong>:data:api</strong> and <strong>:data:real</strong> / <strong>:data:fake</strong> together.</li><li><strong>ui</strong> - could define reusable parts of UI for the feature (optional).</li><li><strong>demo</strong> - standalone app, uses <strong>:fake</strong> to quickly check how the feature is supposed to work.</li></ul><p>In contrast, a <em>core library</em> could have much humble structure, by convention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*Y8y9EbGmU2pMn2UPeAFLZA.png" /></figure><p>I recommend keeping this big picture in mind while reading the long story below.</p><h4>Feature’s public interface - :api module</h4><p>So, let’s wrap up what we have for now. I have just mentioned a couple of entities that play a central role in Architecture: <em>FeatureApi</em> (or <em>CoreLibApi</em>), <em>Interactor</em> and <em>Repository</em>. We will discuss each of them below, but let’s first take a look at what we have inside the feature’s <strong>:api</strong> module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*edac3tBesGawx9xg9TrBRw.png" /></figure><p>That’s pretty much it. <strong>Stock</strong> is just a domain model - a plain Kotlin object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/820dfa3962a920351d2312b50eff34f9/href">https://medium.com/media/820dfa3962a920351d2312b50eff34f9/href</a></iframe><p><strong>StockListFeatureApi</strong> is a particular <em>FeatureApi</em> interface for the <strong>:stock_list</strong> <em>product feature </em>(here <strong>Api</strong> is just a marker interface, read below):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75cd344ce8ad49fba2b4cf3df9eed70c/href">https://medium.com/media/75cd344ce8ad49fba2b4cf3df9eed70c/href</a></iframe><p>This exposes <strong>StockListInteractor</strong> (basically, for DI) - a particular <em>FeatureInteractor</em> interface for the <strong>:stock_list</strong> <em>product feature</em> - to anyone else who would like to use the functionality of the <strong>:stock_list</strong> <em>product feature</em>. So, <em>Interactor</em> is essentially a single and the only <em>entry point</em> to access the functionality of the feature. For example (let’s suppose we use RxJava for data flow):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c429f961141f95fac67a6b1a724cdd16/href">https://medium.com/media/c429f961141f95fac67a6b1a724cdd16/href</a></iframe><p>Hence, the <strong>:stock_list</strong> <em>product feature’s</em> public functionality includes methods to get a list of stocks and a single stock by its ticker.</p><blockquote>Interactor (or FeatureInteractor) — represents a single entry point to the feature’s functionality. It declares how to interact with the feature.</blockquote><p>That’s it for <strong>:api</strong> module: a set of public <em>domain models</em>, <em>FeatureApi</em> and <em>Interactor</em> interfaces. The former declares a particular <em>Interactor</em>, the latter exposes the public interface of the feature’s functionality. Pretty much every feature, either <em>product feature</em> or <em>core library</em>, should have that kind of <strong>:api</strong> module and entities defined inside it. As an example, here is the structure of the <strong>:network:api</strong> module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*DT5q3pefEtu3kGWUGhzFog.png" /></figure><p>And here’s an interface of that particular <em>core library</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f90111305d234efe19316b23c10bdd3/href">https://medium.com/media/5f90111305d234efe19316b23c10bdd3/href</a></iframe><p>A <strong>:network</strong> <em>core library</em> configures an instance of Retrofit and exposes it to the rest of the project. So, one can say that Retrofit is a single and the only entry point to the <strong>:network</strong> <em>core library </em>functionality: one can call it a kind of <em>NetworkInteractor</em>, despite there is no need to add it as an extra layer of abstraction. We will just use an instance of Retrofit directly, so read further.</p><h4>Implementation: :impl and :fake</h4><p>Given an <strong>:api</strong> module of a feature, that defines its public interface, it’s time to provide an implementation of that interface. That’s the purpose of the <strong>:impl</strong> module: it provides a real implementation for the <em>Interactor</em>.</p><p>In particular, for the <strong>:stock_list:impl </strong>module we could have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/879d75ad0f5ec550523ac1b9337766b9/href">https://medium.com/media/879d75ad0f5ec550523ac1b9337766b9/href</a></iframe><p>For now, let’s just leave it with stub implementation: it could be cumbersome to implement it right away.</p><p>But now we are at the point where we can benefit from having that project structure. For example, we have that draft public interface of the feature in the <em>Interactor</em>, and we would like to prove how it’s supposed to work and give a quick demo, showing off how the data lies along with those new design sketches of version 0.12. The work can go in parallel here. One developer (or a group of developers) will continue filling up the gaps in the real implementation, while the others would rely on <em>fake</em> implementation and show off a <em>demo</em> application based on it. That’s the purpose of the <strong>:fake</strong> module: it provides a <em>fake</em> implementation for the <em>Interactor</em>.</p><p>In particular, for the <strong>:stock_list:fake</strong> module we could have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8984329540f7470a3677fd34d0446f5/href">https://medium.com/media/a8984329540f7470a3677fd34d0446f5/href</a></iframe><p>An important note: it’s necessary to declare dependency from <strong>:api</strong> for both <strong>:impl</strong> and <strong>:fake</strong> modules:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8447a837e907ef2be4b13c910cff76dc/href">https://medium.com/media/8447a837e907ef2be4b13c910cff76dc/href</a></iframe><p>I’m using <em>api</em> dependency configuration here to make all entities from <strong>:api</strong> module visible to any other module that would depend on <strong>:impl</strong> or <strong>:fake</strong>. This will reduce clutter in dependencies and seems to be quite logical.</p><p>It’s time to bind interface and implementation. This is the first time when Dagger 2 comes into play. I’m going to show how’s it done for <strong>:fake</strong> module (same approach for <strong>:impl</strong> module). Thus, two new classes are added in <strong>:stock_list:fake</strong> module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*cX6IKP0V5vB1hy6_s4BiFw.png" /></figure><p>(For <strong>:stock_list:impl</strong> module the structure is the same, there will be <strong>StockListFeatureModule</strong> and <strong>StockListFeatureComponent</strong> under <em>di</em> package).</p><p>Here is the <strong>FakeStockListFeatureModule</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9add50332676ab15c3bbc224844e0840/href">https://medium.com/media/9add50332676ab15c3bbc224844e0840/href</a></iframe><p>It’s a <em>Dagger Module</em> that actually binds the interface <strong>StockListInteractor</strong> with its implementation - in that particular case, a <em>fake</em> implementation. Note that I mark every <em>public </em>binding with <strong>@Reusable</strong> annotation. That will guarantee lazy initialization and a single instance for every <em>public</em> binding because of the way they are accessed. We will discuss this later.</p><p>Every <em>Dagger Module</em> must be installed in some <em>Dagger Component</em>. Here it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab62a2ee789d8e4d505cf1f18be45bdc/href">https://medium.com/media/ab62a2ee789d8e4d505cf1f18be45bdc/href</a></iframe><p>There is a bunch of points worth noting. The <em>Component</em> extends <em>FeatureApi</em> (here <strong>StockListFeatureApi</strong> in particular), so it’s responsible for holding an “instance” of a particular feature, and that instance exposes the public interface of that feature (normally, a getter method for an <em>Interactor</em>). The Component, in turn, <em>manages the lifecycle</em> of the whole feature. For now, just keep this in mind.</p><p>A <em>Module</em> (here <strong>FakeStockListFeatureModule</strong>) is installed in the Component, making the latter aware of how to provide an implementation of <em>Interactor</em> (or whatever else is exposed through the <em>FeatureApi</em> interface). I will call this Dagger Module a <em>FeatureModule</em>, and this Dagger Component a <em>FeatureComponent</em>. Please, keep these definitions in mind.</p><p>According to the <a href="https://dagger.dev/dev-guide/testing.html">Dagger 2 Guidelines for Testing</a>, Feature Module is responsible for a provision of a published binding with a reasonable alternative. Each one gets its own Module. <em>FeatureInteractor</em> is obviously a published binding, and since there are both its fake and real implementations, it does have reasonable alternatives. The Architecture just follows the guide. We will also discuss how it helps in testing later.</p><p>So, how could we use <em>fake</em> implementation? As proof of concept, or to quickly check how that new appearance looks like on a particular device, or to test some functional behaviour of this particular feature, or whatever else we need to do with that functionality, a <strong>:demo</strong> module comes into play.</p><p>A <strong>:demo</strong> module represents a standalone Android application that is used to <em>quickly</em> verify a particular work made on a feature under development. Quickly, without rebuilding the world. Fail fast, as the pragmatic approach indicates. This is possible because <strong>:demo</strong> module depends on <strong>:fake</strong> module.</p><p>In <strong>:demo</strong> <em>build.gradle.kts</em> we declare the following dependency:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d0b0b055ad4fc7a5a11a9f37bcfcbc5/href">https://medium.com/media/6d0b0b055ad4fc7a5a11a9f37bcfcbc5/href</a></iframe><p>And we can demonstrate and test the essentials of the feature: how its public interface (<em>Interactor</em>) should work and its UI appearance. Let’s talk about it now.</p><h4>Demo App</h4><p>For the demo app, we have a single Activity that shows a list of <em>fake</em> stocks. See the screenshot at the beginning of this article.</p><p>Following the naming conventions, we have <strong>StockListDemoActivity</strong> and some UI stuff, such as <strong>StockListAdapter</strong> and <strong>StockActivityDemoBinding</strong> (I use <em>viewBinding</em>) - they just do the UI job we don’t bother.</p><p>Pay attention to the part with <strong>inject() </strong>call in the following code snippet (the rest is about UI):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d4cca3984d8d9645dca4f47bf8b6745/href">https://medium.com/media/4d4cca3984d8d9645dca4f47bf8b6745/href</a></iframe><p>Note the use of <strong>DaggerFakeStockListFeatureComponent</strong> here. It’s an implementation of <strong>FakeStockListFeatureComponent </strong>which we’ve discussed before. It provides a <em>fake</em> implementation of the <strong>:stock_list</strong> feature, given by <strong>StockListFeatureApi</strong> (which is <strong>StockListFeatureComponent</strong> actually), that exposes <strong>StockListInteractor</strong> which is actually implemented via <strong>FakeStockListInteractor</strong> under the hood.</p><p>In order to inject Activity’s properties, here is the Component <strong>StockListDemoActivityComponent</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aad64ab2ff96096dd7438dd091ec6057/href">https://medium.com/media/aad64ab2ff96096dd7438dd091ec6057/href</a></iframe><p>This Component declares a dependency on a particular feature, specifying the <em>FeatureApi</em> in the list of dependencies and in a factory method. In this case, we’re going to use a fake implementation of <strong>:stock_list</strong> feature, so we declare a dependency from <strong>StockListFeatureApi</strong>. And as we’ve already seen, that dependency is fulfilled with the <strong>FakeStockListFeatureComponent</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9528f3c2bffd3db408d4771e3e1735f3/href">https://medium.com/media/9528f3c2bffd3db408d4771e3e1735f3/href</a></iframe><p>Thus, our <strong>StockListDemoActivityComponent</strong> is able to access the functionality of the <strong>:stock_list</strong> feature via its public interface given by <strong>StockFeatureApi</strong> and, in particular, by the <strong>StockFeatureInteractor</strong>. The latter is normally injected in the ViewModel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6816258d68f75c2f4f1abf5a8e78d4f/href">https://medium.com/media/f6816258d68f75c2f4f1abf5a8e78d4f/href</a></iframe><p>And now we can call <strong>StockListInteractor::stocks()</strong> to get (fake) data.</p><p>Demo application comes in handy to quickly review the feature’s functionality or UI appearance. A clear and short list of dependencies allows to build it fast without rebuilding the world, while the real implementation can be developed in parallel. Let’s now talk about the real implementation in detail.</p><h4>Structure of Data layer</h4><p>Juggling with fake data is fun, but we have to deal with the real one as well because we actually want to build a useful application. Let’s quickly recall what we have left behind in <strong>:stock_list:impl</strong>. It’s a stub implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/879d75ad0f5ec550523ac1b9337766b9/href">https://medium.com/media/879d75ad0f5ec550523ac1b9337766b9/href</a></iframe><p>In order to fill these gaps, we need a solid foundation of what is the source of data. The data comes from the <em>data layer</em>, which has the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSbKxWo9Lh7AFffrIZAl3g.png" /></figure><p>We are already familiar with the <em>Interactor</em>. To give it realistic implementation, I’m going to introduce a couple of new entities:</p><ul><li><em>UseCase</em> - represents a single task over the data. It’s <strong>stateless</strong>. One or many use-cases belong to a <em>FeatureInteractor</em>, which coordinates them. Use-cases address the <em>Repository</em>.</li><li><em>Repository</em> (<em>FeatureRepository</em>) - a handler over the sources of data. It coordinates between remote and local data sources, applies cache policies and performs mapping between <em>domain</em> and <em>data</em> models. Repository serves as a single source of data.</li></ul><p>Let’s use these entities to organize the data flow from the source to Interactor. As declared in <strong>StockListInteractor</strong>, there are two methods: <strong>stocks()</strong> and <strong>stock(String)</strong>. This actually determines all the use-cases we need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*agLb3uEsU03rJED1DEuljw.png" /></figure><p>Given these use-cases, it’s now possible to implement the Interactor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c2e7eb3f88d847e2e61c1364ec55a3d/href">https://medium.com/media/9c2e7eb3f88d847e2e61c1364ec55a3d/href</a></iframe><p>To execute a <em>UseCase</em>, the <strong>source()</strong> method is called (possibly with parameters like in the second example). I’ve called the method “source” because I rely on reactive data flow using RxJava. It&#39;s not a big deal to re-implement this using Kotlin Coroutines or something else.</p><p>A quick look into <em>UseCase</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4909fa73c4efe2197f58f1ae2523627/href">https://medium.com/media/d4909fa73c4efe2197f58f1ae2523627/href</a></iframe><p><strong>GetStocksUseCase</strong> would look similar. What’s interesting here? Along with some Kotlin extensions for simplicity, there is a reference to <em>Repository</em> - <strong>StockListRepository</strong>. And the <strong>SchedulersFactory</strong>. The latter is just a wrapper over thread dispatchers, it’s purpose could be illustrated in the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c8bcdb3bbce1cd0a24a6d43998ac7ad/href">https://medium.com/media/2c8bcdb3bbce1cd0a24a6d43998ac7ad/href</a></iframe><p>I believe this is quite self-explanatory. <em>UseCase</em> represents a single task and it also encapsulates what thread that task is executed in and what thread that task’s results are delivered (observed). As an extra benefit, thread handling is completely hidden from the users of a UseCase in its implementation. Neither Interactor should bother about coordination of threads, nor fewer experienced developers will step on a rake reasoning about what should go first - <strong>subscribeOn()</strong> or <strong>observeOn()</strong> (without loss of generality, the same if true for Kotlin Coroutines’ Dispatchers).</p><p>Let’s back to <em>Repository</em>. First of all, recall the structure of the <strong>:stock_list</strong> feature, paying attention on the <strong>:stock_list:data:api</strong> module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*EedUh-qZDhSw1j19JrY_Qw.png" /></figure><p>Similar to what we have in <strong>:api</strong> module (<em>FeatureApi</em> and <em>FeatureInteractor</em>), in <strong>:data:api</strong> there are <em>FeatureDataApi</em> and <em>FeatureRepository </em>(simply <em>Repository</em>)<em> </em>interfaces. Treat them in the same sense - <em>FeatureDataApi</em> exposes <em>FeatureRepository</em> for DI, and the <em>FeatureRepository</em> is just an interface to the <em>Data Layer</em> of a particular feature. They’re quite straightforward to declare:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df2a4d68e8d105afe56e3c701edd252/href">https://medium.com/media/3df2a4d68e8d105afe56e3c701edd252/href</a></iframe><p>Note the analogy with <strong>StockListFeatureApi</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9adaffc77141f1415a392edf8e5e3d5/href">https://medium.com/media/c9adaffc77141f1415a392edf8e5e3d5/href</a></iframe><p>Note the analogy with <strong>StockListInteractor</strong>. And now things should become clear for us - a particular <em>UseCase</em> makes a particular call to <em>Repository</em> for data. That’s it. But please, don’t think that Repository is a sort of <a href="https://en.wikipedia.org/wiki/Anemic_domain_model">anemic model</a>, containing little to no business logic! This is not true, just take a look at its <a href="https://github.com/orcchg/SampleAndroidArchAtScale/blob/master/feature/stock_list/data/real/src/main/kotlin/com/orcchg/sample/atscale/stocklist/data/DefaultStockListRepository.kt">real implementation on Github</a>. This is rarely just a bunch of simple method delegations.</p><p>As usual, there is a fake implementation of the data layer, given by <strong>:data:fake</strong> module, and a single (or many) real implementation(s), given by <strong>:data:real</strong> (and others) module. Why there could be more than just a single real implementation? Imagine that for the purposes of Stocks App we are using public API, such as <a href="https://finnhub.io/">Finnhub Open API</a>. We are not limited to use another, for example, <a href="https://mboum.com/">MBOUM</a>. Thus, we’d need a couple of real implementations - <strong>:data:finnhub</strong> and <strong>:data:mboum</strong>. Add here a fake implementation from <strong>:data:fake</strong>, and now we have 3 different implementations for the data layer, so we need a common interface for it. That’s the purpose of the <strong>:data:api</strong> module and the <em>FeatureRepository</em> interface.</p><p>Both <strong>:data:fake</strong> and <strong>:data:real</strong> would have the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*2ETC6uSSeAyK6kJVcsrNpQ.png" /></figure><p>I won’t go into details here. Just to give a brief explanation, there are <em>remote</em> and <em>local</em> packages: the former contains a bunch of data models tied to network API (<strong>StockEntity</strong>), a converter from the data model to domain model (<strong>StockEntity</strong> -&gt; <strong>Stock</strong>) and declarations of the network calls in an interface to be consumed by the Retrofit (<strong>StockListRest</strong>). Package <em>local</em> contains all the stuff need for local caching. Here I’m using Room from Jetpack. We don’t bother with the details of it in this article, if you need so - please <a href="https://github.com/orcchg/SampleAndroidArchAtScale">check it on Github</a>.</p><p>To give you an idea behind the Repository, take a look at this snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbe227052bf3bceb61ea4af8a8e23167/href">https://medium.com/media/fbe227052bf3bceb61ea4af8a8e23167/href</a></iframe><p>The rest is just implementation details. All the data sources - both remote and local - are just injected into the <em>Repository</em> via DI. It’s now up to the implementation to coordinate between these data sources and fulfil the <strong>StockListRepository</strong> interface.</p><h4>Wiring api and implementation of a data layer</h4><p>It’s time to choose between implementations of the data layer of a feature. We need to bind <em>FeatureRepository</em> interface from the <strong>:data:api</strong> module with its implementation from <strong>:data:real</strong> or fake implementation from <strong>:data:fake</strong>. To do so, let’s have an extra module <strong>:data:wiring</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*jsBVHvYSqNzWjuj-83YS7g.png" /></figure><p>Let’s start our consideration from <strong>StockListNetworkModule</strong> Dagger Module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0efb47980aa56efa877daa7c56784398/href">https://medium.com/media/0efb47980aa56efa877daa7c56784398/href</a></iframe><p>Remember when I told you that I’m going to use Retrofit directly from the <strong>:network</strong> <em>core library</em>. It is right here. No need to have <em>NetworkInteractor</em> because it would just add an extra level of indirection here.</p><p>What is <em>really</em> important here is the package of <strong>StockListRest</strong>. And the package of <strong>StockDao</strong>. Since both of these entities vary between real(s) and fake implementations, they appear in both <strong>:data:real</strong> and <strong>:data:fake</strong> modules. So, from the <strong>:data:wiring</strong> module’s perspective, in order to have a single code in it to provide <strong>StockListRest</strong> (and <strong>StockDao</strong>, if any) via DI, the package of <strong>StockListRest</strong> (and similar entities) <em>must be the same</em> across the implementation modules. Thus, <strong>:data:wiring:StockListNetworkModule</strong> could be written only once, and depending on the chosen data layer’s implementation, it will provide whatever instance of <strong>StockListRest</strong> the project needs.</p><p>See how one can switch between the implementation of a data layer: just replace the <strong>:data:real</strong> to another dependency in <strong>:data:wiring</strong> <em>build.gradle.kts</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8524148873683e037b7a809434ba0b3d/href">https://medium.com/media/8524148873683e037b7a809434ba0b3d/href</a></iframe><p>The change at this line will replace one binding to another given the same package for both of them.</p><p>The last thing is to bind <em>FeatureRepository</em> interface with its implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6306e29730b8f42a27129336a89cab4/href">https://medium.com/media/c6306e29730b8f42a27129336a89cab4/href</a></iframe><p>For example, <strong>DefaultStockListRepository</strong> will use <strong>StockListRest</strong> provided by the <strong>StockListNetworkModule</strong> Dagger Module. The instance of <strong>StockListRest</strong> is defined by the aforementioned Gradle project dependency.</p><p>This Dagger Module is installed in the <em>FeatureDataComponent</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ef9111c8ff535950ea76c3c474bf11/href">https://medium.com/media/65ef9111c8ff535950ea76c3c474bf11/href</a></iframe><p>Retrofit comes from <strong>NetworkCoreLibApi</strong> dependency and is used to provide an instance of the <strong>StockListRest</strong> interface, injected into an instance of the <strong>StockListRepository</strong>. The latter is actually exposed via <strong>StockListDataApi</strong> to DI, hence this Component.</p><p>We have already seen that we use Dagger <em>component dependencies</em> quite extensively. Here we declare a dependency on <strong>:network</strong> <em>core library</em> (as <strong>NetworkCoreLibApi</strong>). For the <strong>:stock_list:demo</strong> app you probably remember the dependency on <strong>StockListFeatureApi</strong>, which provides a feature’s <em>Interactor</em>.</p><p>Where are all these dependencies come from, given the fact that the project’s structure is highly modularized and the modules are quite isolated from each other? We’re at the finish line now and it’s about time to discuss, how features could depend on each other and why all these <em>FeatureApi</em> and other DI stuff.</p><h4>Dependency management</h4><p>So, how do we actually implement the app? Remember how I wrote an implementation of an Activity from the <strong>:demo</strong> module. Scroll back to refresh your memory. Basically, we have an Activity (or Fragment) that injects its properties using some Dagger Component. For example, let’s say we have a ViewModel that injects some <em>FeatureInteractor</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ba6ebbfc64f870f724598c3a7eda2f3/href">https://medium.com/media/6ba6ebbfc64f870f724598c3a7eda2f3/href</a></iframe><p>This ViewModel depends on <strong>StockListInteractor</strong>. The ViewModel itself is injected in the Activity (Fragment) indirectly via ViewModelFactory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d1696752f00997fc42b435973b1c0a0/href">https://medium.com/media/6d1696752f00997fc42b435973b1c0a0/href</a></iframe><p>And finally, this ViewModelFactory is injected in the Activity (Fragment) the following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b19f2854208eb96ecda4402570dd889d/href">https://medium.com/media/b19f2854208eb96ecda4402570dd889d/href</a></iframe><p>The <strong>DaggerStockListFragmentComponent</strong> is in charge here of injecting ViewModelFactory and the provider for the ViewModel. It uses <strong>@Inject</strong> constructors to provide an instance of these classes.</p><p>But since ViewModel requires an instance of the <strong>:stock_list</strong> feature’s <em>Interactor</em> (<strong>StockListInteractor</strong>), we need a way to provide it for DI. We need to make it visible to the <strong>DaggerStockListFragmentComponent</strong>. This is the point where Dagger’s <em>component dependencies</em> shine.</p><p>Take a look at line 9. This is a factory call <strong>create()</strong> to instantiate the <strong>DaggerStockListFragmentComponent</strong>. Let’s see some details:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c8b06ef2e85ba31e97d17d474fc5507/href">https://medium.com/media/6c8b06ef2e85ba31e97d17d474fc5507/href</a></iframe><p>The method’s argument indicates a dependency on <strong>StockListFeatureApi</strong>. The latter is actually responsible for the provision of the <strong>StockListInteractor</strong> needed for the ViewModel.</p><p>That’s pretty much it! We declare all <em>FeatureApis</em> that expose <em>Interactors</em> (or other bindings) we need in the component dependencies’ list. And all we need is to obtain these <em>FeatureApis</em> somehow. Take a look at this line again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b6a01b4022f6405fffb4bef73beaba2/href">https://medium.com/media/6b6a01b4022f6405fffb4bef73beaba2/href</a></iframe><p>It addresses an inscrutable “api” to get an instance of FeatureApi required.</p><p>What is “api” here? It’s an <em>ApiContainer</em>. A map between <em>FeatureApi</em> and an instance of Dagger Component that actually implements that <em>FeatureApi</em>. The map is generic, so each <em>FeatureApi</em> extends a marker-interface <em>Api</em> for that reason. The only way to access some global storage on Android (and the <em>ApiContainer</em> is actually such storage) is to access it through Application.</p><p>This is done via base Fragment (or Activity) class for brevity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64d5e0f6d5c1e848c0b5ef1223b8fe2f/href">https://medium.com/media/64d5e0f6d5c1e848c0b5ef1223b8fe2f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc2a6c6967da560986ef0e39e8b11cf0/href">https://medium.com/media/cc2a6c6967da560986ef0e39e8b11cf0/href</a></iframe><p>Thus, <em>ApiContainer</em> holds all features (in terms of instances of <em>FeatureComponents</em>), and is represented as the <em>ApiContainer</em> interface, which is actually implemented by the Application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f97e2e0f553e0a224d56b326f0f415d6/href">https://medium.com/media/f97e2e0f553e0a224d56b326f0f415d6/href</a></iframe><p>The puzzle is assembled now. To recap, the Application serves as an <em>ApiContainer</em> - a map &lt;<em>FeatureApi</em> : Dagger<em>FeatureComponent</em>&gt;, Fragments (or Activities) could address that <em>ApiContainer</em> at any time to retrieve a <em>FeatureApi</em> and hence - a <em>FeatureInteractor</em> they need. And inject them. Since these <em>Interactors</em> are reusable (recall a <strong>@Reusable</strong> annotation), and <em>ApiContainer</em> is actually a singleton (since the Application is a singleton), it is guaranteed that for each access of a particular <em>FeatureApi</em> the same instance of <em>FeatureInteractor</em> is obtained through it. One feature — one instance to access its functionality.</p><h4>ApiContainer in details</h4><p>The map &lt;<em>FeatureApi</em> : Dagger<em>FeatureComponent</em>&gt; is actually implemented using Dagger Multibindings. Let’s take a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5efd4dbd78bda7f262646c53ebb77e9/href">https://medium.com/media/f5efd4dbd78bda7f262646c53ebb77e9/href</a></iframe><p>Here I define a new Dagger Module <strong>FeatureApiModule</strong> that lists the map entries for each <em>product feature</em> in the project. The <strong>@FeatureApis</strong> annotation indicates that this particular entry goes into <strong>@FeatureApis</strong> map declared in the Application. Note a couple of extra annotations here: <strong>@CoreApis</strong> and <strong>@DataApis</strong>. Since our <strong>:stock_list</strong> <em>product feature</em> depends on some <em>core libraries</em> and the <em>Repository</em> from the <strong>:stock_list:data:api</strong> module, we get these bindings from the additional maps:</p><p>The <strong>@DataApis</strong> map contains entries for &lt;<em>FeatureDataApi</em> : Dagger<em>FeatureDataComponent&gt;:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b714d9936c8a949ddd4ab9f7933fa61/href">https://medium.com/media/6b714d9936c8a949ddd4ab9f7933fa61/href</a></iframe><p>As we see, it could use bindings from <em>core libraries</em>. They reside in the <strong>@CoreApis</strong> map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c53900ad336d0f0ed28ad1112bbe7f0/href">https://medium.com/media/2c53900ad336d0f0ed28ad1112bbe7f0/href</a></iframe><p>Finally, <strong>@FeatureApis</strong> map is assembled and injected into the Application, using the <strong>AppComponent</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e4ef937c1f071086eef7d9913fa1753/href">https://medium.com/media/3e4ef937c1f071086eef7d9913fa1753/href</a></iframe><p>And as a finishing touch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440ac3989ab4530758cf7eec5fbbb449/href">https://medium.com/media/440ac3989ab4530758cf7eec5fbbb449/href</a></iframe><p>The picture should be full now, indeed. The Architecture makes a difference between the functionality and presentation (UI) of a feature. Each part gets its own module. The feature’s functionality has a public interface that is highly accessible to any other feature via <em>ApiContainer</em>. This is normally a <em>FeatureInteractor</em>. So, there could be many UIs, many screens and demo apps, but everyone could access any feature’s public functionality at any time given the project structure the Architecture declares.</p><p>And there is even nothing special about Android dynamic features. See an <a href="https://github.com/orcchg/SampleAndroidArchAtScale/tree/master/feature/stock_details">example on Github</a>. For the dynamic feature, it’s natural to depend on <strong>:app</strong> module. And if we need to reuse the functionality of a particular dynamic feature somewhere else, it’s very convenient to separate that functionality from the UI. The former goes into <strong>@FeatureApis</strong> map and becomes publicly accessible, the latter goes to the Android dynamic feature module.</p><h4>Navigation</h4><p>An important aspect of every multimodular project is navigation. In my opinion, the best way to navigate in Android app is to have a single MainActivity and use deeplinks with the help of <a href="https://developer.android.com/guide/navigation">Jetpack’s Navigation</a>. We won’t consider navigation in this article, but it’s not difficult at all. Just <a href="https://github.com/orcchg/SampleAndroidArchAtScale/tree/master/navigation">check it out</a> on Github, there is a dedicated <strong>:navigation</strong> module containing a navigation graph in XML. The graph is then set in MainActivity, the rest is quite straightforward.</p><h4>Testing</h4><p>We’ve already seen how fake implementation helps us to test the functionality and/or appearance of a feature via demo apps. But this is more about manual testing, so let’s discuss auto testing and how the structure and the layers of the Architecture help in this.</p><p>Recall <em>UseCase</em> — a stateless object that represents a piece of work in isolation. A single task. Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05f6d2047a9c7efd93a892e2f5d0b589/href">https://medium.com/media/05f6d2047a9c7efd93a892e2f5d0b589/href</a></iframe><p>This sample is easy and could give the impression that a <em>UseCase</em> is anemic model, but one can imagine a more sophisticated case. Suppose we have a multistep login flow checking some tokens in a secure way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fec88c416fe93c07725efabf95bbd355/href">https://medium.com/media/fec88c416fe93c07725efabf95bbd355/href</a></iframe><p>I don’t give you any details about its constructor params, just let’s suppose <strong>TrustedLoginUserUseCase</strong> uses some external services injected via DI. What is important here is the fact the <em>UseCase</em> handles all the steps needed for trusted login internally and gives us an atomic piece of work. So, if we need to perform trusted login, we don’t bother any details and just call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ec904e60b31067c987e3e381c2e1845/href">https://medium.com/media/8ec904e60b31067c987e3e381c2e1845/href</a></iframe><p>From the client-side perspective, <strong>TrustedLoginUserUseCase</strong> looks quite atomic and encapsulated. <em>Interactor</em> just coordinates the work between use-cases. Without <em>UseCase</em> all the logic would be exposed in the Interactor’s implementation leading to clutter. How could we even test the steps in isolation? This justifies that I have introduced a <em>UseCase</em>. So, writing a unit test for it is very easy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6640bfc9fb7b6ceb3e22104a9737c2ed/href">https://medium.com/media/6640bfc9fb7b6ceb3e22104a9737c2ed/href</a></iframe><p>Thus, the trusted login logic could be tested in isolation given a <em>UseCase</em>. Unit-testing for <em>Repository</em> is also simple. <a href="https://github.com/orcchg/SampleAndroidArchAtScale/blob/master/feature/stock_list/data/real/src/test/kotlin/com/orcchg/sample/atscale/stocklist/data/TestStockListRepository.kt">Check it out on Github</a>.</p><p>Speaking about integration tests, using mocks is <a href="https://www.reddit.com/r/androiddev/comments/d05di8/do_you_use_the_impl_suffix_if_you_only_have_one/ez8cs5r?utm_source=share&amp;utm_medium=web2x&amp;context=3">not recommended</a>. So, <em>fakes</em> substitute real objects. Our Dagger Modules that provide real and fake <em>Interactors</em> and <em>Repositories</em> (and possibly other entities) are organized for testability according to the official <a href="https://dagger.dev/dev-guide/testing.html">Dagger Testing guidelines</a>. Both these entities have reasonable alternatives and we choose between different Dagger Modules (recall <strong>FakeStockListFeatureComponent</strong> from <strong>:stock_list:fake</strong> and <strong>StockListFeatureComponent</strong> from <strong>:stock_list:impl</strong> modules) installed in Dagger Components for <strong>:demo</strong> and real apps.</p><p>Let’s see another demonstration of the testing capabilities of the Architecture. I’m going to test ViewModel. Our testing configuration would have a special Dagger Component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2829a76fbcb125598a7ec642a41c3ab8/href">https://medium.com/media/2829a76fbcb125598a7ec642a41c3ab8/href</a></iframe><p>In this Component, I’ve installed Modules that provide fake implementations. In particular, a fake <em>Interactor</em> is used. Below is the example test for ViewModel that is using a fake <em>Interactor</em> injected into ViewModel’s constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/731b5818fe010430ca55e81d55c2ad49/href">https://medium.com/media/731b5818fe010430ca55e81d55c2ad49/href</a></iframe><p>This example is intended to show, how dependency injection helps in testing. ViewModel has been constructed using fakes, so it’s now ready to be tested. We can go deeper and have an integration test for our ViewModel where the real Interactor is used but with the fake Repository on the other end. See the <a href="https://github.com/orcchg/SampleAndroidArchAtScale/blob/master/feature/stock_list/demo/src/test/kotlin/com/orcchg/sample/atscale/stocklist/demo/TestIntegrationStockListViewModel.kt">source code</a> on Github.</p><h4>Conclusion</h4><p>The main idea of the Architecture is the statement that any product feature (or core library) could have its functionality separated from the UI and shared with the others within the whole project. This allows us to reuse features’ functionality flexibly, test it in isolation using demo apps, and write tests easier. Separation of the UI and the logic in different modules also simplifies usage of Android dynamic features and increases a degree of the project’s modularity, which is good for build performance and dependency management. The Architecture follows the principles of Clean Arch, but the presentation layer is still open to extension or alter: it’s possible to choose between MVP, MVI or MVVM, though the latter is preferred due to ubiquitous usage of Jetpack. An explicit separation between API and implementation is good when we need to have multiple implementations. It is also good for testing and for better clarity. The Architecture is scalable: every feature has the same structure and usage, and there is no systematic debt that could accumulate over time as the project grows. And last, but not least, DI is also an important foundation of Architecture. Thanks to Dagger 2, it’s compile-time safe.</p><p>Feel free to check the <a href="https://github.com/orcchg/SampleAndroidArchAtScale">full sample out on Github</a>. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92208e95c0ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>