Balancing Usability and Security with Python
Multi-factor authentication (MFA) is one of the most effective defenses against credential theft. But “MFA for everyone, everywhere” is not free. Every prompt costs seconds of employee time, increases help-desk tickets, and pushes frustrated users toward workarounds. Meanwhile, some user groups hold almost nothing worth stealing.
In this article we turn the question “Who should be forced to use MFA?“ into a small optimization problem and solve it exactly in Python.
1. The Problem Setting
A company has 14 user segments, such as executives, IT administrators, finance staff, contractors, and cafeteria staff. For each segment $i$ we know:
- $n_i$: number of users
- $p_i$: annual probability that a user’s credentials get compromised
- $L_i$: average loss per compromise (dollars)
- $e_i$: the fraction of compromises that MFA prevents (effectiveness)
- $f_i$: annual usability cost per user (lost time, support tickets, workarounds)
- $D_i$: one-time-per-year deployment and operation cost for the segment
The decision variable is $x_i \in {0,1}$, where $x_i = 1$ means MFA is enforced for segment $i$.
Benefit (expected annual loss avoided):
$$
B_i = n_i , p_i , L_i , e_i
$$
Cost (usability plus deployment):
$$
C_i = n_i , f_i + D_i
$$
Problem 1: unconstrained optimum. Maximize the net value:
$$
\max_{x \in {0,1}^N} \sum_{i=1}^{N} x_i ,(B_i - C_i)
$$
Problem 2: budget-constrained optimum. Maximize the avoided loss while keeping the total friction and deployment cost within a budget $K$:
$$
\max_{x \in {0,1}^N} \sum_{i=1}^{N} x_i B_i \quad \text{s.t.} \quad \sum_{i=1}^{N} x_i C_i \le K
$$
Problem 2 is a classic 0-1 knapsack problem. With $N = 14$ there are only $2^{14} = 16{,}384$ possible policies, so we can enumerate all of them and obtain the provably exact optimum.
The residual risk after applying a policy $x$ is:
$$
R(x) = \sum_{i=1}^{N} n_i p_i L_i ;-; \sum_{i=1}^{N} x_i B_i
$$
For the 3D visualization, we also use the per-user view. Let $r_i = p_i L_i e_i$ be the expected loss avoided per user. Enforcing MFA on one user is worthwhile when:
$$
v = r - f > 0
$$
2. Source Code
The entire program is a single script. To avoid a slow Python loop over $2^{14}$ policies, the enumeration is fully vectorized: every policy is encoded as a bitmask, expanded into a binary matrix $M \in {0,1}^{2^N \times N}$, and evaluated with two matrix-vector products.
1 | import numpy as np |
3. Code Walkthrough
Step 1: Defining the data
Each tuple in rows describes one segment. The values are deliberately realistic in shape: executives and IT administrators have a high compromise probability and an enormous loss per incident, while cafeteria and warehouse kiosk staff have tiny loss values. Contractors are interesting because they have a high compromise probability but also the highest friction ($90 per user per year), as they use unmanaged devices and many different tools.
The two core formulas are computed directly as pandas columns: benefit is $n_i p_i L_i e_i$ and cost is $n_i f_i + D_i$. We also derive net, ratio (benefit divided by cost), and risk_per_user, which is $r_i = p_i L_i e_i$ and is used later in the 3D plots.
Step 2: Exact optimization by vectorized enumeration
The key line is:
1 | M = ((codes[:, None] >> np.arange(N)) & 1).astype(np.float64) |
codes holds the integers $0, 1, \dots, 2^N - 1$. Shifting each integer right by $0, 1, \dots, N-1$ bits and masking with & 1 extracts every bit, so row $k$ of M is the binary representation of $k$. That row is exactly one enforcement policy $x$. The resulting matrix has $16{,}384$ rows and $14$ columns.
Then M @ B and M @ C compute $\sum_i x_i B_i$ and $\sum_i x_i C_i$ for all policies at once. This replaces a Python loop of $16{,}384 \times 14$ iterations with two BLAS calls that finish almost instantly, which is the speed-up for the time-consuming part.
best_freemaximizestot_benefit - tot_cost, which solves Problem 1.best_budgetmasks out infeasible policies with $-\infty$ and maximizes the benefit, which solves Problem 2.
Because this is a brute-force search over the entire space, the answer is guaranteed to be the global optimum.
Step 3: Greedy heuristic
For larger organizations (say, 60 or more segments), $2^N$ enumeration is impossible. The standard fallback is a greedy rule: sort segments by benefit-to-cost ratio and add them while the budget allows. We include it as a comparison to show how close the cheap heuristic comes to the exact optimum. I also require $B_i > C_i$, so the heuristic never buys a segment that destroys value.
Step 4: Baselines and summary
summarize evaluates any policy mask and returns the number of segments, covered users, total benefit, total cost, net value, and residual expected loss $R(x)$. We compare five policies: no MFA, MFA for everyone, the unconstrained optimum, the budget optimum, and the greedy policy.
Step 5: Pareto frontier
For 120 budget levels from $0$ up to the cost of covering everyone, we find the maximum achievable benefit among all feasible policies. Converting this to residual loss gives the best possible security level for each amount of friction we are willing to accept.
Step 6: Sensitivity analysis
Real estimates of friction and effectiveness are uncertain. We sweep a friction multiplier (0.5x to 3x) and an effectiveness scale (0.5x to 1.0x) and count how many segments still satisfy $B_i > C_i$. This shows how robust the recommended scope is.
Step 7: Visualization
All six panels are drawn into one figure, so a single plt.show() produces the whole picture. Panels 4 and 5 are 3D plots created with projection="3d".
4. Console Output
=== Segment data and per-segment economics ===
segment users benefit cost net ratio enforce_free enforce_budget
Executives 40 582000.0 3900 578100.0 149.23 True True
IT administrators 60 1176000.0 6200 1169800.0 189.68 True True
Finance staff 120 359100.0 9600 349500.0 37.41 True True
HR staff 80 136800.0 6500 130300.0 21.05 True True
Contractors 150 207000.0 17500 189500.0 11.83 True True
Engineers 400 304000.0 23000 281000.0 13.22 True True
Customer support 300 121500.0 16000 105500.0 7.59 True True
Sales 250 67500.0 16000 51500.0 4.22 True True
Marketing 100 8100.0 7000 1100.0 1.16 True True
Legal 30 68400.0 2850 65550.0 24.00 True True
Back-office clerks 350 6160.0 25500 -19340.0 0.24 False True
Warehouse kiosk staff 500 1280.0 23500 -22220.0 0.05 False False
Interns 80 1056.0 7200 -6144.0 0.15 False True
Cafeteria staff 120 135.0 6100 -5965.0 0.02 False True
=== Policy comparison ===
policy segments users_covered benefit cost net residual_loss
No MFA 0 0 0.0 0.0 0.0 3167980.0
MFA for everyone 14 2580 3039031.0 170850.0 2868181.0 128949.0
Unconstrained optimum 10 1530 3030400.0 108550.0 2921850.0 137580.0
Budget optimum (<= $150,000) 13 2080 3037751.0 147350.0 2890401.0 130229.0
Greedy by ratio (same budget) 10 1530 3030400.0 108550.0 2921850.0 137580.0
Greedy / exact benefit ratio under budget: 0.9976
Enforced (budget optimum): Executives, IT administrators, Finance staff, HR staff, Contractors, Engineers, Customer support, Sales, Marketing, Legal, Back-office clerks, Interns, Cafeteria staff
Not enforced (budget optimum): Warehouse kiosk staff
5. Graph Output

6. Reading the Results
What the numbers say
Without any MFA, the expected annual loss across the whole company is about $3.17 million. Enforcing MFA for everyone avoids about $3.04 million of that, at a total cost of about $171 thousand, leaving a residual expected loss of about $129 thousand.
The unconstrained optimum is different. It enforces MFA in 10 of the 14 segments, covering 1,530 of 2,580 users. Its cost is only about $109 thousand, and its net value is about $2.92 million. That beats “MFA for everyone” (net about $2.87 million) by roughly $54 thousand per year, even though it leaves slightly more residual loss (about $138 thousand). The four skipped segments are back-office clerks, warehouse kiosk staff, interns, and cafeteria staff. For these groups the expected loss avoided is smaller than the friction and deployment cost, so forcing MFA destroys value.
Why the budget optimum enforces more segments
With a budget of $150 thousand, the exact optimum enforces 13 segments and skips only the warehouse kiosk staff. This looks surprising at first, because Problem 2 maximizes avoided loss, not net value. When the budget is not tight, adding a low-value segment still increases total benefit a little, so the solver keeps adding until the budget is nearly exhausted (about $147 thousand spent). If your goal is cost-effectiveness rather than maximum risk reduction, Problem 1 is the right formulation. If your goal is “reduce risk as much as the friction budget allows,” Problem 2 is the right one. Making this distinction explicit is an important part of a policy discussion.
The greedy heuristic reaches the same set as the unconstrained optimum, and its benefit is 99.76% of the exact budget optimum. For a large number of segments, this makes greedy a practical and nearly lossless substitute.
Panel (1): Net value per segment
The bar chart makes the asymmetry obvious. IT administrators and executives generate net values in the hundreds of thousands to over a million dollars. Engineers, finance staff, and contractors form a solid middle tier. Marketing sits barely above zero (a net of about $1.1 thousand, benefit-to-cost ratio of 1.16), which marks the boundary. The four red bars at the bottom are the segments where MFA enforcement costs more than it saves.
Panel (2): Benefit versus cost on a log-log scale
Points above the dashed diagonal are worth enforcing. The bubble size is proportional to the number of users. IT administrators and executives sit far above the line, with benefit-to-cost ratios of roughly 190 and 149. The low-risk, high-headcount groups (warehouse kiosk, back-office, cafeteria) sit below it. Marketing hugs the diagonal, which shows how sensitive the decision is for borderline groups.
Panel (3): The security-versus-usability frontier
The curve shows the lowest achievable residual loss for each cost level. It drops steeply at first, because the cheapest segments (administrators, executives, finance) remove most of the risk, and then flattens into a long tail. Beyond roughly $100 thousand, each additional dollar buys almost no extra risk reduction. The markers confirm this: the unconstrained optimum, the greedy policy, and the budget optimum all lie almost on the flat part of the curve, while “MFA for everyone” is the farthest to the right with essentially no extra security to show for it. This chart is the best one to show to management, since it turns the “security versus convenience” argument into a concrete curve.
Panel (4): 3D surface of per-user net value
The surface is the plane $v = r - f$ over the plane of expected loss avoided $r$ and friction $f$, with a translucent gray plane at $v = 0$. The decision boundary is the diagonal line $r = f$ where the surface crosses the gray plane. Everything where the surface is above the plane is worth protecting. The geometry shows that MFA scope should be set by the ratio of risk to friction, not by an organization-wide blanket rule.
Panel (5): Segments in 3D
Each segment is a point in the space of loss avoided per user, friction per user, and headcount. Green points are recommended for enforcement and red ones are not. The green points are spread along the high-risk axis, with administrators and executives at the far end, while red points collect near the origin of the risk axis, including the largest groups by headcount such as warehouse kiosk staff. The third axis makes a practical point: the red segments are not small, so skipping them removes a large amount of user-facing friction.
Panel (6): Sensitivity heatmap
The horizontal axis multiplies the friction estimate and the vertical axis scales MFA effectiveness. The color and white contour labels show how many segments still pass the $B_i > C_i$ test. The baseline (red dot) corresponds to the 10 segments found above. Moving right (friction becomes more painful) or down (MFA becomes less effective) shrinks the enforced scope, and the core group of high-risk segments stays enforced in almost every scenario. This means the headline recommendation, “always enforce MFA for administrators, executives, finance, HR, legal, and contractors,” is robust, while the decision for borderline groups such as marketing and sales depends heavily on how well you can estimate friction.
7. Takeaways
Casting MFA scope as a 0-1 optimization gives three practical lessons.
- Risk-based scoping beats blanket enforcement. Skipping only four low-risk segments raised the net value by about $54 thousand per year in this example while removing friction for 1,050 users.
- The marginal value curve is steep and then flat. Most of the risk reduction comes from a small number of high-value segments, so these should be enforced first and with the strongest factors (for example, phishing-resistant authenticators).
- Borderline groups need better data. The sensitivity map shows that the uncertain decisions are the ones near $B_i \approx C_i$. Measuring real friction costs through help-desk tickets and login time is more valuable than refining the risk model for groups that are already far from the boundary.
For larger organizations, replace the brute-force enumeration with a dynamic-programming knapsack solver or an integer programming library, and add constraints such as regulatory requirements that force MFA for certain segments regardless of economics.











