Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A multi-tenant Spring service must choose a tax calculation strategy per tenant from configuration, with several implementations as beans. Design the selection mechanism, including startup validation and defaults.

Each tax strategy is a Spring bean implementing TaxStrategy with a stable key() method. A selector injects List<TaxStrategy>, builds a Map from key to strategy and fails startup on duplicate keys, then validates at startup that every tenant's configured key exists. An explicit default covers tenants without a setting and is logged when used, strategies stay stateless because they are shared singletons, and we test each strategy on its own and the selection logic once.

Why this question is asked

In a multi-tenant service, one wrong lookup means a customer is charged the wrong tax, which is a legal problem, not just a bug. The usual failure is not in the tax maths; it is in the wiring: a misspelt key in a tenant's configuration that only shows up when that tenant's first invoice is created, or two beans that claim the same key so one silently wins. Interviewers ask this design question to see whether we make those failures impossible, or at least visible at startup. In this answer, we will define the strategy contract, build the registry from Spring beans, validate tenant configuration at startup, handle defaults on purpose, keep strategies thread-safe, and plan the tests.

1The Strategy Contract

A strategy here is one way of calculating tax, such as German VAT, a US sales tax provider, or no tax for exempt tenants. All of them implement one interface. The key() method returns a stable identifier that tenants refer to in configuration. Stable matters: it is stored in configuration and maybe in a database, so we never derive it from the class name, which would change in a refactoring.

Java
public interface TaxStrategy {
String key(); // "eu-vat", "us-sales", "exempt"
TaxResult calculate(TaxRequest request); // pure: no fields changed
}
@Component
class EuVatStrategy implements TaxStrategy {
private final VatRates rates; // immutable, loaded once
EuVatStrategy(VatRates rates) { this.rates = rates; }
public String key() { return "eu-vat"; }
public TaxResult calculate(TaxRequest r) {
BigDecimal rate = rates.forCountry(r.country()); // DE -> 0.19
return new TaxResult(r.net().multiply(rate).setScale(2, RoundingMode.HALF_UP));
}
}

2Building the Registry From Beans

Spring can inject every bean of a type as a list. The selector turns that list into a map once, in its constructor. We deliberately avoid Collectors.toMap with a merge function, because silently keeping one of two strategies with the same key is exactly the bug we want to catch. Plain toMap throws IllegalStateException on a duplicate key, but we write the loop ourselves to give a clear message.

Java
@Component
public class TaxStrategySelector {
private final Map<String, TaxStrategy> byKey = new HashMap<>();
private final Map<String, String> tenantKeys; // tenantId -> key, from configuration
private final String defaultKey;
TaxStrategySelector(List<TaxStrategy> strategies, TaxProperties props) {
for (TaxStrategy s : strategies) {
TaxStrategy previous = byKey.putIfAbsent(s.key(), s);
if (previous != null) {
throw new IllegalStateException("Duplicate tax strategy key '" + s.key() + "': "
+ previous.getClass().getName() + " and " + s.getClass().getName());
}
}
this.tenantKeys = Map.copyOf(props.tenants());
this.defaultKey = props.defaultStrategy();
validate();
}
}

Notice that the map is built once and never changed after the constructor, so it is safe to read from many request threads without locking. We could also use Spring's ability to inject a Map<String, TaxStrategy>, but that map is keyed by bean name, which is an implementation detail; an explicit key() keeps configuration independent of how beans are named.

3Validating Tenant Configuration at Startup

The most important design choice is to fail fast. If tenant acme is configured with eu-vatt, we want the application to refuse to start in the deployment pipeline, not to fail at 2 a.m. on acme's first invoice. So the constructor checks every tenant's key, and the default key, against the registry.

Java
private void validate() {
if (!byKey.containsKey(defaultKey)) {
throw new IllegalStateException("Default tax strategy '" + defaultKey + "' does not exist");
}
List<String> broken = tenantKeys.entrySet().stream()
.filter(e -> !byKey.containsKey(e.getValue()))
.map(e -> e.getKey() + "=" + e.getValue())
.toList();
if (!broken.isEmpty()) {
throw new IllegalStateException("Unknown tax strategy for tenants " + broken
+ "; known keys are " + byKey.keySet());
}
}
// Startup with tenants.acme=eu-vatt fails:
// Unknown tax strategy for tenants [acme=eu-vatt]; known keys are [eu-vat, us-sales, exempt]
Step throughStartup and request-time selection
  1. Collect all TaxStrategy beansInjected as a List
  2. Duplicate key?Two beans return the same key()
    YesFail startup with both class namesNoBuild the key map
  3. Every tenant key and the default known?Checked against the map
    YesApplication startsNoFail startup listing bad tenants
  4. Request arrives for a tenantTenant id from the request context
  5. Tenant configured?Look up tenantKeys
    YesUse its strategyNoUse the default and log it

5 steps in order. Play them, or step through them one at a time.

The message lists the bad entries and the valid keys, so whoever reads the failed deployment log can fix it in one step. If tenant configuration lives in a database and can change at runtime, the same validation must run on every write, through the admin API, so a bad value is rejected before it is saved.

4Defaults, Done on Purpose

Some tenants will have no setting, for example new tenants created before finance has assigned them a scheme. We do not want an exception for those, but we also do not want a hidden fallback. So the default is a named property, validated like the others, and every use is logged with the tenant id and counted in a metric. A dashboard of default usage tells finance which tenants still need configuring.

Java
public TaxStrategy forTenant(String tenantId) {
String key = tenantKeys.get(tenantId);
if (key == null) {
log.info("Tenant {} has no tax strategy; using default '{}'", tenantId, defaultKey);
defaultUsed.increment(); // Micrometer counter
key = defaultKey;
}
return byKey.get(key);
}
selector.forTenant("acme").key(); // eu-vat
selector.forTenant("newco").key(); // exempt, logged as a default

Whether a default should exist at all is a business decision. In some regulated setups, charging no tax by default is worse than refusing the sale, so the honest default might be a strategy that rejects the request with a clear error. The mechanism stays the same; only the chosen key changes.

5Thread Safety and Testing

Spring beans are singletons by default, so one EuVatStrategy instance serves every tenant and every request at once. Strategies must therefore be stateless: no fields that change during calculate(), only immutable configuration loaded at construction. A strategy that cached the last country in a field would mix up two tenants' requests under load. If a strategy needs per-request data, it belongs in the TaxRequest argument.

Testing follows the structure. Each strategy gets plain unit tests with tax examples, constructed with new and no Spring context, because it is just a class with inputs and outputs. The selector gets a small set of tests run once: duplicate keys fail, an unknown tenant key fails, a missing default fails, an unconfigured tenant gets the default. Finally one Spring Boot test starts the real context with the production configuration files, which catches a broken key before deployment.

6Follow-up questions

Why not use @Qualifier or bean names to choose the strategy?

Qualifiers choose at injection time, once, but we need to choose per request based on the tenant. Bean names would work as keys, but they tie configuration to how beans are named in code, and renaming a class or method would silently break a tenant. An explicit key() is a deliberate, stable contract.

How would you add a new strategy for one tenant without redeploying everyone?

A new strategy is new code, so it needs a deployment, but feature flags or configuration can keep it unused until finance switches the tenant over. Because the selector validates keys at startup and on configuration writes, the switch can only point to a strategy that exists.

What if a strategy needs to call an external tax service?

Then it holds a thread-safe client as an immutable dependency, and calculate() makes the call. We add timeouts and a clear failure mode, because tax lookups sit in the checkout path. The selector design does not change; it still just maps keys to beans.

7Conclusion

In this answer, we designed tax selection around a TaxStrategy interface with a stable key(), a selector that builds a map from the injected list and fails on duplicate keys, and startup validation that every tenant key and the default exist. Defaults are explicit, logged and counted. Strategies stay stateless because they are shared singletons, each strategy is unit tested on its own, and the selection logic is tested once.

What to say in the interviewAbout 100 seconds aloud

Open with

I would make each tax calculation a Spring bean that implements a TaxStrategy interface with two methods: calculate, and a key method that returns a stable string like eu-vat.

Then, if they want more

Tenants reference that key in configuration. Then I would have a selector bean that takes List of TaxStrategy in its constructor and builds a map from key to strategy. If two beans return the same key, the constructor throws with both class names, so a copy-paste mistake can never silently pick one.

In the same constructor I validate the configuration: every tenant's key must exist in the map, and so must the default key. If anything is wrong, the application fails to start with a message listing the bad tenants and the valid keys, so we find it in the pipeline, not on a customer's invoice.

If tenant settings can change at runtime, the admin API runs the same validation before saving. For tenants with no setting, I use an explicit default from configuration, log every time it is used and count it in a metric, so finance can see who still needs configuring.

In some regulated cases the right default might even be a strategy that refuses the sale. Because Spring beans are singletons shared by all requests, the strategies must be stateless, with only immutable configuration.

For testing, each strategy gets plain unit tests, the selector gets a few tests for duplicates, unknown keys and defaults, and one context test loads the real configuration.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A multi-tenant Spring service must choose a tax calculation strategy per tenant from...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/77527e7152/