The Three-Zone Architecture: Structure for Chaos

Stop building monoliths that shatter. Build systems with crumple zones.

Three-zone architecture visualization for medical software

A note on this series: This is a series of my software engineering philosophies focusing on the intersection of the regulated life science sector and the traditional software design paradigm. No proprietary projects or algorithms are shared; insights are based on my personal experiences and opinions shared within are my own and do not represent the view of my past or current employer.

In Part 1, I argued that making robust and compliant medical software is rather paradoxical: you want to have more control in an inherently complex and often chaotic high-entropy world. Here I want to dive into my take on how to reconcile them - by embracing the entropic dynamics. I’d like to show you what that looks like in practical terms.

But lets first digress momentarily and think about how modern cars are designed (No I am not sorry that I have ADHD): they are not safe by being universally rigid; they increase safety by intelligently controlling where they break1. They have a rigid engine block by nature of the engine itself, a passenger cabin designed for structured deformation, and crumple zones at the extremities intended to fail (crumble) on purpose to maximize passenger survivability in a crash, to serve as an impact energy absorber (instead of the human body). The parallel here is that the intended failure is a feature - it is not a bug…

The same can be said in designing SaMD in a broader sense. Now, instead of talking about the chaotic energy created by impact, we have to deal with the high-entropy state of the clinical reality. If we cannot avoid it, why not embrace it and leverage it? Why not architect it also to have an intentional “crumple zone”? By the way, this is by no means a new or never thought of idea - just a perspective of highlighting the thinking from a perpendicular angle.

Now, let’s get serious - before we dive into the “why-so-serious” pseudo-code illustrations of the principles.

I think the architecture conceptually consists of three zones: the critical core with the lowest entropy and highest control, the clinical interface, where you start to adapt and expand from the core with more entropy - yet still totally robust, and the outer integration zone, where failure actually becomes the feature and the guardrail.

This architecture aligns with IEC 62304’s need to separate software of different safety levels and meets FDA cybersecurity guidance by implementing layered defenses and controlled interfaces. It addresses the core challenge in medical software: balancing the need for deterministic, verifiable algorithms in life-critical decisions with operating in environments filled with legacy systems, creative users, and unpredictable integrations. By designing zones with varying entropy tolerances, we can implement more effective validation strategies. This perspective also recognizes that a single architecture can’t optimize correctness, human factors, and resilience simultaneously - it’s simply flawed thinking to begin with. Of course, you still have to make this compliant and make it submission-ready, which probably deserves its own blog series.

Okay, with our attention battery running low again - let’s loosen up a bit. We will use this hypothetical but totally legit and helpful SaMD as an example to cover the framework. We will build a Focus Restoration Device™: a SaMD that monitors your cognitive load by secretly judging your broswer usage pattern and delivers “therapeutic” electrical nudges at totally appropriate body parts before you doom-scroll into the abyss. You will need it for this oh-look-what’s-that-zap! longer piece - buckle up.

Zone 1: The Critical Core

This is your engine block—where attention metrics become medical-grade zap decisions. Here, entropy is the enemy. This zone is pure, deterministic, and has zero external dependencies. No network calls, no database queries, no file I/O. It’s a mathematical fortress that could run on a calculator from 1982.

// The Zap Calculator™ - where math meets medical intervention
pub struct AttentionCore {
    danger_zone_threshold: f32,      // Point of no return
    gentle_nudge_threshold: f32,     // "Hey buddy, you okay?"
    max_therapeutic_voltage: f32,    // Legal limits apply
}

impl AttentionCore {
    pub fn calculate_therapeutic_voltage(&self, chaos: ChaosMetrics) -> ZapPrescription {
        // FDA-approved algorithm (patent pending)
        let doom_score = self.quantify_doom_spiral(chaos);

        match doom_score {
            s if s > 0.95 => ZapPrescription::DefibrillateBrain {
                voltage: self.max_therapeutic_voltage,
                duration_ms: 50,  // Just a tickle, promise
                message: "Your dopamine receptors have filed for divorce",
            },
            s if s > self.danger_zone_threshold => ZapPrescription::ModerateJolt {
                voltage: s * self.max_therapeutic_voltage * 0.5,
                duration_ms: 20,
                message: "17 tabs? In this economy?",
            },
            s if s > self.gentle_nudge_threshold => ZapPrescription::TinyZap {
                voltage: 0.1,  // Like rubbing socks on carpet
                duration_ms: 10,
                message: "Just checking you're still alive",
            },
            _ => ZapPrescription::NoZap,  // You're actually working! Miracle!
        }
    }

    fn quantify_doom_spiral(&self, chaos: ChaosMetrics) -> f32 {
        // Scientific formula discovered by procrastination researchers
        (chaos.reddit_minutes * 0.3 +
         chaos.tab_explosion_rate * 0.3 +
         chaos.scroll_velocity_kmh * 0.2 +
         chaos.alt_tab_frequency * 0.2).min(1.0)
    }

    pub fn calculate_recovery_duration(&self, doom_depth: f32) -> Duration {
        // Exponential recovery because brains are drama queens
        Duration::from_secs((doom_depth.powf(2.5) * 420.0) as u64)
    }
}

#[derive(Clone, Copy)]
pub struct ChaosMetrics {
    reddit_minutes: f32,       // Normalized suffering units
    tab_explosion_rate: f32,   // Tabs per minute (TPM)
    scroll_velocity_kmh: f32,  // Yes, we measure in km/h
    alt_tab_frequency: f32,    // The ADHD coefficient
}

The beauty of Zone 1 is its testability. With no side effects, you can throw property-based testing, formal verification, even mathematical proofs at it2. This is where FDA’s “software of unknown provenance” fears disappear—because provenance is total.

Zone 2: The Clinical Interface

Surrounding the core is your passenger cabin—where humans actually interact with the system. This is where users negotiate with the algorithm (“I’m researching!”), where “productivity” gets creatively redefined, and where someone claims watching YouTube tutorials about productivity counts as being productive.

Zone 2 absorbs human creativity without letting it corrupt the core’s medical decisions.

pub struct AttentionInterface {
    core: AttentionCore,
    user_profile: UserProfile,
    excuse_detector: ExcuseDetector,  // ML-powered BS filter
}

impl AttentionInterface {
    pub async fn intercept_human_chaos(&mut self, activity: BrowserActivity) -> Intervention {
        // First, decode what user is "actually" doing
        let real_activity = self.excuse_detector.see_through_bs(&activity);

        // "I'm reading documentation" (on reddit.com/r/programmerhumor)
        if real_activity.pretending_to_work_score > 0.8 {
            return Intervention::BustedMode {
                message: "Nice try. Reddit isn't documentation.".into(),
                evidence: self.collect_evidence(&activity),
                action: Action::GraduallyFadeScreen,
            };
        }

        // Convert messy human behavior to clean medical metrics
        let chaos = self.humanness_to_metrics(&real_activity);

        // Let the core make the medical decision
        let prescription = self.core.calculate_therapeutic_voltage(chaos);

        // But deliver it with empathy (sort of)
        self.deliver_intervention_with_style(prescription, &real_activity)
    }

    fn deliver_intervention_with_style(
        &self,
        zap: ZapPrescription,
        activity: &RealActivity
    ) -> Intervention {
        match zap {
            ZapPrescription::DefibrillateBrain { voltage, .. } => {
                // Nuclear option with flair
                Intervention::EmergencyMode {
                    action: self.choose_nuclear_option(&self.user_profile),
                    recovery: self.core.calculate_recovery_duration(voltage),
                    epitaph: "Here lies productivity: 2025-2025".into(),
                }
            },
            ZapPrescription::ModerateJolt { message, .. } => {
                // Firm but fair
                Intervention::InterventionMode {
                    action: Action::ReplaceAllTabsWithCalmingKittens,
                    message,
                    offer_snooze: false,  // No negotiations
                }
            },
            ZapPrescription::TinyZap { message, .. } => {
                // Gentle nudge
                Intervention::SoftNudge {
                    suggestion: self.generate_gentle_suggestion(&activity),
                    passive_aggressive_level: 3,
                    message,
                }
            },
            ZapPrescription::NoZap => Intervention::Nothing,  // Carry on, hero
        }
    }

    fn choose_nuclear_option(&self, profile: &UserProfile) -> Action {
        // Personalized torture based on user preferences
        match profile.intervention_style {
            Style::Gentle => Action::PlayMeditationMusic,
            Style::Moderate => Action::RickRollAllTabs,
            Style::Aggressive => Action::EmailBossWithScreenshot,  // We're not savages
            Style::Chaos => Action::InstallVim,  // The ultimate productivity trap
        }
    }
}

Zone 2 can fail horizontally—if the excuse detector breaks, core calculations continue. If the UI crashes, voltage calculations persist. This zone is about graceful degradation, not perfection.

Zone 3: The Integration Layer

The outermost layer is your crumple zone—where true chaos lives. Browser APIs that return quantum states, Chrome eating RAM like Pac-Man, Firefox pretending it’s 2010. This zone expects failure as the default state3.

use tokio::time::{timeout, Duration};

pub struct BrowserChaosWrangler {
    quarantine: Vec<String>,  // The island of misfit data
    sanity_checker: SanityChecker,
}

impl BrowserChaosWrangler {
    pub async fn wrangle_browser_madness(&mut self, raw: RawBrowserState) -> Option<BrowserActivity> {
        // Chrome says you have ∞ tabs? Seems legit.
        if raw.tab_count < 0 || raw.tab_count > 9999 {
            self.quarantine.push(format!(
                "Chrome claims {} tabs. Chrome needs therapy.", raw.tab_count
            ));
            return None;
        }

        // Check for impossible physics
        if raw.scroll_speed > SPEED_OF_LIGHT {
            self.quarantine.push("User scrolling at relativistic speeds".into());
            return None;
        }

        // Sanitize the madness into something medical-grade
        let maybe_sane = BrowserActivity {
            url: self.detoxify_url(&raw.url)?,
            duration: self.unbreak_time(&raw.duration),
            tab_count: raw.tab_count.clamp(0, 500) as u32,  // Be reasonable
            scroll_events: self.filter_quantum_scrolls(&raw.events),
            user_agent: self.decode_user_agent_lies(&raw.user_agent),
        };

        // Give browser APIs 100ms before assuming they're hung (optimistic)
        match timeout(Duration::from_millis(100), self.validate(maybe_sane)).await {
            Ok(Some(valid)) => Some(valid),
            Ok(None) => None,
            Err(_) => {
                self.quarantine.push("Browser API went to get milk".into());
                None  // Tuesday in browser-land
            }
        }
    }

    fn detoxify_url(&self, url: &str) -> Option<String> {
        // Filter out the truly cursed URLs
        match url {
            u if u.contains("😂") => None,  // Emoji domains are a cry for help
            u if u.len() > 2048 => None,     // That's not a URL, that's a novel
            u if u == "about:blank" => Some("user.gave.up".into()),
            u if u.contains("file:///") => Some("local.procrastination".into()),
            _ => Some(url.to_string()),
        }
    }

    fn filter_quantum_scrolls(&self, events: &[ScrollEvent]) -> Vec<ScrollEvent> {
        events.iter()
            .filter(|e| {
                // Remove physically impossible scroll events
                e.velocity < 10000.0 &&  // Not teleporting
                e.direction != ScrollDirection::Diagonal &&  // We live in 2D
                !e.timestamp.is_nan()  // Time is real, JavaScript
            })
            .cloned()
            .collect()
    }

    fn decode_user_agent_lies(&self, agent: &str) -> String {
        // Every browser pretends to be every other browser
        if agent.contains("Mozilla") && agent.contains("Chrome") && agent.contains("Safari") {
            "browser-having-identity-crisis".into()
        } else {
            agent.to_string()
        }
    }
}

Zone 3 is built with the assumption that everything is broken until proven otherwise. It parses defensively, validates obsessively, and fails silently—because in the integration layer, failure is not an exception; it’s Tuesday.

These zones can’t just chat freely—that’s how entropy spreads like COVID at a browser convention. Communication follows strict patterns that act as entropy filters:

// Zone 3 -> Zone 2: Event Pattern (throw chaos over the wall)
pub enum BrowserChaosEvent {
    TabSplosion { count: u32, survivors: Vec<String> },
    ScrollApocalypse { velocity: f32, direction: ScrollDirection },
    TheGreatCrash { last_words: String },
}

// Zone 2 -> Zone 1: Query Pattern (asking the oracle)
pub trait MedicalComputation {
    fn calculate_therapeutic_voltage(&self, chaos: ChaosMetrics) -> ZapPrescription;
    fn calculate_recovery_duration(&self, doom_depth: f32) -> Duration;
    fn is_user_salvageable(&self, metrics: ChaosMetrics) -> bool;
}

// Zone 1 -> Zone 2: Command Pattern (medical orders)
pub enum CoreDirective {
    InitiateEmergencyProtocol { shock_level: Severity },
    DemandUserAttention { ultimatum: String },
    ScheduleDigitalDetox { duration: Duration, no_cheating: bool },
}

The iron rule: Zone 3 never talks directly to Zone 1. Ever. No exceptions. Not even for “just this one critical feature.” That path is how entropy reaches your core and medical decisions become corrupted by browser madness.

You don’t need a full rebuild to implement this. Start here:

  1. Identify your true core (it’s smaller than you think—usually the 5% that actually does the thing)
  2. Build a quarantine zone around it using Result types and therapy sessions
  3. Exile all I/O operations to the outer darkness where they belong
  4. Install airlocks between zones (circuit breakers, but cooler sounding)

This isn’t a rewrite; it’s an exorcism. Think of it as refactoring for sanity.

Remember the paradox from Part 1? We need perfect control in an imperfect world. This approach doesn’t eliminate this tension: it channels it. Like those automotive crumple zones, we don’t prevent the crash; we control where the system breaks - and use it to our advantage.

The FDA gets its validated core that makes medical decisions about cognitive intervention. Users get an interface that speaks their language of excuses and procrastination. The chaos of browser APIs and their quantum behavior gets absorbed by the integration layer. Everyone wins because we stopped fighting entropy and started surfing it.


Next: Part 3 - Testing the Untestable: When Edge Cases Are The Norm (Coming Soon)

References

Footnotes

  1. Huang, M. (2002). “Vehicle crash mechanics.” CRC Press. The principle of controlled deformation in automotive safety directly parallels the need for controlled failure zones in software architecture.

  2. Woodcock, J., Larsen, P. G., Bicarregui, J., & Fitzgerald, J. (2009). “Formal methods: Practice and experience.” ACM Computing Surveys, 41(4), 1-36. Formal verification becomes tractable when applied to pure, isolated functions without side effects.

  3. Humble, J., & Farley, D. (2010). “Continuous delivery: Reliable software releases through build, test, and deployment automation.” Addison-Wesley. The principle of designing for failure at the boundaries while protecting core functionality.