Weighing unnecessary network calls against simplicity and expected cost.

Ever since I first started talking about Impueriem Sandwiches, and later Recawr Sandwiches, the most common question has been: What if I need to fetch some data, make a decision based on that data, and so on?

I've already responded to such questions a few times:

As I have also stated, the problem with selling this design pattern is exactly that it's not a general-purpose architecture. No design pattern is. I am, therefore, always happy when I receive particular questions about it, because I believe that the more examples I give, the easier it is to see the value.

A letter from a reader #

Sam Frances recently wrote to me:

"Lets say you have a pure function like the following:

def choose_command(config, permissions):
    if "my_feature_flag" in config and "my_perm" in permissions:
        return FooCommand()
    return BarCommand()

"This is nice and pure, easily testable etc. My real example is more complex, of course, but I'm not free to share that.

"I'm envisaging a impureim sandwich:

# config already in scope
permissions = fetch_permissions()  # impure
command = choose_command(config, permissions)  # pure
command.execute()  # impure

"However, you can probably already see an inefficiency there. Say permissions requires a network call, which you don't want to make unless needed. I.e. if the feature flag isnt there, you didn't need to fetch permissions. But if you fetch permissions from within choose_command(), you lose functionality purity, have to mock to test it, etc.

def choose_command(config):
    if "my_feature_flag" in config and "my_perm" in fetch_permissions():
        return FooCommand()
    return BarCommand()

"Is there a functional way to address cases like this? Or do we just swallow a slight inefficiency in return for functional purity?"

The short answer is that the easiest solution is indeed to swallow a slight inefficiency, but I still find it important to elaborate.

Optimize for the common path #

Software architecture is often a question of trade-offs. Lose something to gain something. I'm often ready to sacrifice small inefficiencies if I can thereby keep things simpler. A good rule of thumb is to optimize for the common scenario. I have previously discussed this in relation to test failures. I think a similar mindset is often useful when it comes to discussions about Recawr Sandwiches.

People are often, like Sam Frances, concerned about making a network call if there's a risk that the data goes unused. This may be a rational concern, and is certainly worth considering. When, however, analyzing a situation like this one, you should also ask additional questions: How expensive is the network call? How likely is it that the call is wasted? Can the result be cached? What consequences are associated with a wasted network call?

Such questions may have varied answers. Consider the consequences. In the above example, calling fetch_permissions imply a network roundtrip to retrieve a set of permissions. What are the consequences of calling fetch_permissions if we don't need the permissions because the feature flag is off?

Is the problem that it takes a long time, and we are concerned that if we make the user wait too long, he or she will abandon our system in favour of a competitor? Or are we worried that we waste server resources?

The solution we arrive at relate to answers to such questions. If we assume, as I hope is most realistic, that the fetch_permissions call itself is fairly inexpensive, the concern may be mostly related to wasted server resources. If so, however, analyze how much that waste amounts to. Particularly when it comes to feature flags, there ought to be two outcomes:

  • Either the feature becomes permanent, in which case we can eventually remove the feature-flag check altogether. This then implies that the Composition Root needs to call fetch_permissions unconditionally. In this outcome, there are no wasted network calls.
  • The other alternative is that after a period of testing, the feature is turned off again. In that case, the associated code should be deleted. If the call to fetch_permissions was contingent on the flag, that call can be deleted too.

In both cases, the potential inefficiency is temporary.

This analysis may, however, be disingeneous. After all, Sam Frances' example code is a stand-in for something more complicated. Perhaps it's not even related to feature flags. In a more general case, the inefficiency may be permanent: If you choose to always make a network call, even in the cases where you don't need to, you waste some compute and network resources. The question remains: Can you live with such 'waste'? As I discussed in Song recommendations as an Impureim Sandwich, it may be more efficient to add an extra server, or an extra network card, than to make the architecture more efficient but more complicated.

A fat arrow pointing to foo, with two much smaller arrows branching off pointing to bar.

In many cases, if the common scenario (e.g. when the feature flag is raised and the permission is granted) dominates the alternatives (when you may perform the network operation in vain), then it makes sense to accept the slight inefficiency.

Caching #

Another way to deal with an apparent inefficiency related to making a network call is to decrease its cost. Can you cache the data? If so, it may not matter that you call fetch_permissions in vain, because it's essentially only a memory lookup.

It's often surprising what you can cache, particularly if you adopt an eventual-consistency mindset. Even so, you may think: Surely, when it comes to security, caching is unsafe.

You'll be surprised. Most IT security infrastructure relies on caching. X.509 certificates come with an expiry date, until which they are considered valid. In order to deal with certificates that shouldn't have been issued, there's typically also a certificate revocation list that you're supposed to consult, but many don't do that, or at the very least cache the list. There's a reason why various institutions are working on making domain certificates more ephemeral. Even so, a certificate is effectively a cache document, complete with an expiry policy.

If you use OAuth, claims about the security actor are embedded in security tokens. Systems use those claims to make security decisions. How long does an OAuth token live? Usually the lifetime is measured in minutes, and may be as much as an hour.

Back when I worked with WS-Federation and SAML it was the same story.

And back when I worked as an IT pro and sysadmin with an international Windows network, I learned that Kerberos worked essentially the same: All your group memberships would be attached to a security token issued to your session when you logged into Windows. This was nothing but an array of GUIDs, and it would last until you logged out. If a sysadmin made changes to your group memberships, they wouldn't take effect until you logged out and in again. This included membership revocation.

This all sounds dangerous. After all, if you discover that a user is misusing privileges, you can't immediately revoke them. As I understand it, this is a calculated risk in the design, and reflects what I meant by an eventual-consistency mindset. Instead of 'right now', you may have discovered the user's abuse an hour later. In the end, exactly when events happen is random.

This all does sugest, however, that you can aggresively cache credentials. Sam Frances doesn't quite write what fetch_permissions does, but I can only imagine two scenarios.

  • If fetch_permissions retrieves group memmberships or claims related to role-based security, you may already have those as part of a Kerberos, SAML, or OAuth token. In this case, no network hop is involved.
  • Alternatively, fetch_permissions may query for permissions on a particular resource; that is, some Access Control List (ACL) is involved. Again, you may consider how often such ACLs change. If they only change infrequently, then caching may be appropriate.

In the latter case, for a sufficiently small system, all ACLs might actually fit in RAM, in which case you might consider just loading all of them and refreshing the cache periodically.

As usual, when caching is involved, you need to consider how to deal with systems running on more than one server.

I always consider caching an advanced optional architecture that I'd do much to avoid. The good thing about it, though, is that it's a cross-cutting concern, so you should be able to add it to an existing system architecture with only moderate effort.

Combinators #

Another option is to surface the decision to make the network call in such a way that you can make the call conditional in the Composition Root. Although 'we' frown upon introducing branching or looping constructs into the Composition Root, we can sometimes hide them behind a 'combinator'. My article Refactoring registration flow to functional architecture has many examples of those. In the present choose_command example, the combinator is less compelling, but I'll cover it for completeness.

Image refactoring choose_command so that the first conditional is promoted to a separate function:

def has_feature(config):
    return "my_feature_flag" in config
 
 
def choose_command(config, permissions):
    if has_feature(config) and "my_perm" in permissions:
        return FooCommand()
    return BarCommand()

This means that the Composition Root can now make the call conditional on that function:

# config already in scope
permissions = await fetch_permissions() if has_feature(config) else set()  # impure
command = choose_command(config, permissions)  # pure
command.execute()  # impure

Of course this introduces branching into the Composition Root. Is this permitted?

In software architecture, there are no hard rules, so whether this should be considered legal is always up for debate. That said, if you wish to use thresholds as heuristics, some limit values work better than others. Just like the correct number of compiler warnings is zero, the most appropriate boundary value for cyclomatic complexity in the Composition Root is 1 (the lowest possible number). This may seem unnecessarily strict and ideal, but is really based on pragmatism: If you allow any other cutoff, then why not one more? If you allow cyclomatic complexity of 2, then why not 3? If 3, why not 4? At least 1, being the minimum, comes with a mathematical property in its defence.

If we adopt this attitude, then the above Composition Root with an if/else expression is illegal. Can we fix it somehow?

This is where my knowledge of Python is too shallow, so I ported the example to Haskell, which I still use as the gold standard for functional architecture.

permissions <- if hasFeature config then fetchPermissions else pure Set.empty -- impure
let command = chooseCommand config permissions -- pure
execute command -- impure

This, at first glance, is no improvement. Like the Python example, this Composition Root has a cyclomatic complexity of 2. Is there some combinator that enables us to hide the complexity? Yes, we can use the bool case analysis:

permissions <- bool (pure Set.empty) fetchPermissions (hasFeature config) -- impure
let command = chooseCommand config permissions -- pure
execute command -- impure

You may think of bool as nothing but a glorified ternary conditional operator, and that this is really cheating. I am sympathetic to such an objection. It does, however, formally reduce the cyclomatic complexity to 1, per the above discussion.

I'm not aware that Python (or my other go-to languages F# and C#, for that matter) comes with an equivalent bool function in its base library. Even so, you could always add it yourself (and cover it with unit tests). If you don't like the name bool, you may find inspiration in the knowledge that this function is the Boolean catamorphism. Perhaps names like cata_bool or fold_bool work better for you?

# config already in scope
permissions = await fold_bool(has_feature(config), fetch_permissions, set())  # impure
command = choose_command(config, permissions)  # pure
command.execute()  # impure

This is possible in Python, too, but less elegant. This is not a recommendation; only an exploration of options.

Relationship with algorithm analysis #

The concern behind many questions related to the Sandwich patterns is one of efficiency. It seems wrong to make a network call (or other expensive calculation) if you don't need it. This is a reasonable concern, but first, the usual caveats apply: If you are concerned about perfomance, measure. Only address the inefficiency if you can measure a problem. I'm sure I don't need to quote Knuth here.

Assume that you have already measured the size of the problem, and it turns out that it is, in fact, one that should be addressed. My point about optimizing for the common path relates to algorithmic analysis of expected versus worst-case running time. If you can live with a few outliers, then opting for a good expected running time is the better solution. Only solve the problem if the expected running time is bad, or you can't live with the outliers (that is, the worst-case running time).

Bringing caching into the mix is reminiscent of ammortized analysis. Every cache miss has a high cost, which is then ammortized over several cache hits. The more cache hits, the better the ammortization.

Conclusion #

A design pattern is never universal. It's

"a solution to a problem in a context."

Even so, a common question that arises from the Sandwich patterns is how to deal with conditional data fetches. The answer often lies in challenging the underlying assumption. Such questions usually imply that it's important that you only make a secondary query once you have the result of the first query.

Suprisingly often it proves fruitful to examine that assumption. Once you start taking into consideration the actual cost of making the second query, it may turn out that it's not worth the trouble trying to avoid it. Particularly if algorithmic analysis shows that the expected or ammortized cost is low.

This article is an example of such analysis. It demonstrates that simplification may be found if you combine analytical and pragmatic thinking.

As I have previously asserted,

"a surprisingly large proportion of problems can be rephrased and organised in such a way that the impureim sandwich architecture applies. Actually, I surmise that most problems can be addressed in that way."

The problem is that so far, I see no way to prove that conjecture. Instead, I attempt to argue it case-by-case, because my own experience is that the pattern is much more applicable than people realize. This article, then, is one such argument.

I welcome further examples, should you have some.



Wish to comment?

You can add a comment to this post by sending me a pull request. Alternatively, you can discuss this post on Twitter or somewhere else with a permalink. Ping me with the link, and I may respond.
Published: Monday, 30 November 2026 06:50:00 UTC