Network Segmentation Design
Flat networks are convenient, and that convenience is what attackers exploit. Once a single laptop or IoT sensor is compromised, nothing stops the intruder from walking toward the database tier. Splitting the network into segments breaks those paths, but every segment boundary adds a firewall hop, extra latency, and more rules to maintain.
This article turns that trade-off into a combinatorial optimization problem and solves it in Python on a concrete 26-host enterprise network.
1. The Example Problem
The network has $n = 26$ hosts with the following roles.
| Role | Hosts | Exposure | Asset value |
|---|---|---|---|
| Web | 4 | high | medium |
| App | 5 | medium | medium-high |
| DB | 4 | low | critical |
| Auth (AD/IdP) | 2 | low | critical |
| Mgmt (jump/admin) | 2 | low | high |
| Client (workstations) | 6 | very high | low |
| IoT | 3 | very high | very low |
Each host $i$ has an exposure score $e_i$ (how likely it is to be compromised first) and an asset value $v_i$ (how much damage follows if an attacker reaches it). The traffic volume between hosts $i$ and $j$ is $T_{ij}$, and $F_{ij}=\mathbb{1}[T_{ij}>0]$ marks a flow that needs a firewall rule if it crosses a boundary.
The decision variable is a segment assignment $x_i \in {0,\dots,K_{\max}-1}$ for every host. The goal is to choose $x$ so that attackers have few paths, legitimate traffic crosses few boundaries, and the design stays manageable.
2. Mathematical Model
Attack-path weight. The damage potential of a host pair is
$$
S_{ij} = e_i v_j + e_j v_i .
$$
Lateral-movement risk. Hosts in the same segment can reach each other freely, while hosts in different segments are reachable only with a small leak probability $\varepsilon$:
$$
R(x) = \varepsilon \sum_{i<j} S_{ij} + (1-\varepsilon)\sum_{i<j} S_{ij},\mathbb{1}[x_i = x_j].
$$
Latency. Traffic crossing a segment boundary passes through an inspection point and pays a delay $\delta$:
$$
L(x) = \delta \sum_{i<j} T_{ij},\mathbb{1}[x_i \neq x_j].
$$
Operational cost. Each segment costs $c_s$ to run, and each cross-boundary flow needs a rule that costs $c_r$:
$$
O(x) = c_s,K(x) + c_r \sum_{i<j} F_{ij},\mathbb{1}[x_i \neq x_j],
$$
where $K(x)$ is the number of non-empty segments.
Scalarized objective. The three terms are normalized by their worst-case reference values (a flat network for risk, full isolation for latency and operations) and then combined:
$$
J(x) = w_R,\frac{R(x)}{R_{\text{flat}}} + w_L,\frac{L(x)}{L_{\text{all}}} + w_O,\frac{O(x)}{O_{\text{all}}}, \qquad \sum w = 1 .
$$
The constraint is $|{i : x_i = k}| \le M$ for every segment $k$, so no segment grows into a new flat network.
This is a graph-partitioning problem with a non-linear cost and is NP-hard in general, so the code uses simulated annealing with a single-host relocation move. A move is accepted with probability
$$
P_{\text{accept}} = \min!\left(1,; e^{-\Delta J/\tau_t}\right), \qquad \tau_t = \tau_0\left(\frac{\tau_1}{\tau_0}\right)^{t/N}.
$$
Why the incremental update matters. Recomputing $J$ from scratch costs $O(n^2)$ per proposal. Instead, the code keeps three matrices that store, for every host, the sum of $S$, $T$ and $F$ toward each segment:

Moving host $i$ from segment $a$ to segment $b$ then changes the objective components by

which is an $O(1)$ lookup. Only the accepted moves pay an $O(n)$ column update. This is the optimized version used below, and it makes many restarts and parameter sweeps cheap.
3. Full Source Code
1 | import time |
4. Code Walkthrough
Section 1: building the network. Hosts are generated by role, and each role has its own exposure and asset-value profile with a little random jitter. Traffic is generated from a role-affinity matrix AFF. Web-to-App and App-to-DB are heavy, Auth talks to many roles at moderate volume, and IoT mostly talks to Mgmt. A pair of hosts gets a flow with probability proportional to its affinity, and the volume is exponentially distributed. This produces the heavy-tailed, role-structured traffic seen in real enterprise networks. The seed is fixed, so the dataset is identical on every run.
Section 2: metrics and normalization. metrics(x) evaluates $R$, $L$ and $O$ with vectorized boolean masks over the upper triangle. Dividing by $R_{\text{flat}}$, $L_{\text{all}}$ and $O_{\text{all}}$ puts all three terms on a comparable scale, so the weights $w$ express policy rather than unit conversion.
Section 3: the annealer. The first half of anneal builds the three segment-sum matrices seg_s, seg_t and seg_f. Each iteration then does the following:
- Pick a random host
iand a random target segmentb. - Skip the move if it would exceed the size cap.
- Compute the exact change in each cost component with three array lookups.
- Apply the Metropolis rule, and update the matrices only when the move is accepted.
Random numbers are pre-drawn as arrays, which removes Python-level RNG overhead from the loop. Because $\Delta J$ is computed exactly, the final objective(best_x, w) call is a consistency check against the incrementally tracked value. best_of runs several independent restarts and keeps the winner, which guards against unlucky annealing trajectories.
Section 3 (continued): baselines and sweeps. The optimized layout is compared against four reference designs: a flat network, per-host isolation, a role-based layout with one zone per role, and a random layout of six balanced zones. Two sweeps follow. The first changes the maximum allowed number of segments from 1 to 10. The second changes the risk weight $w_R$ from 0.05 to 0.75 while shifting the latency weight, which traces an approximate Pareto frontier.
Section 4: console report. A table compares all designs, followed by the role composition of each optimized segment and the runtime of the experiments.
Section 5: visualization. The six panels are arranged in two rows and three columns. Panels (c) and (d) are 3D plots.
5. Console Output
======================================================================== Hosts: 26 | traffic flows: 131 | total traffic: 463.9 Weights (risk, latency, ops) = (0.5, 0.3, 0.2) | cross-segment leak eps = 0.05 ======================================================================== Design Risk Latency Ops J Zones MaxSize Flat (no segmentation) 1.000 0.000 0.021 0.504 1 26 Per-host isolation 0.050 1.000 1.000 0.525 26 1 Role-based (7 zones) 0.135 0.945 0.540 0.459 7 6 Random (6 zones) 0.179 0.788 0.509 0.428 6 5 Optimized (SA) 0.238 0.336 0.376 0.295 5 8 ------------------------------------------------------------------------ Optimized segments: Segment 0: 1 hosts -> Mgmtx1 Segment 1: 8 hosts -> Clientx5, Authx2, Webx1 Segment 2: 6 hosts -> Webx3, Appx2, Clientx1 Segment 3: 7 hosts -> DBx4, Appx3 Segment 4: 4 hosts -> IoTx3, Mgmtx1 ------------------------------------------------------------------------ Risk reduction vs flat : 76.2 % Latency vs per-host isolation: 66.4 % lower Main SA run (4 restarts) : 3.6 s K-sweep + Pareto sweep : 21.0 s
6. Result Image

7. Reading the Results
Design comparison, panel (f) and the console table
The three trivial designs each fail in a different way.
- Flat network. It has the lowest latency and operating cost, but its risk is normalized to 1.0. Every compromised host has a direct path to every crown jewel.
- Per-host isolation. It drives risk down to the floor set by the leak probability $\varepsilon$, but latency and operations both hit their maximum. Every flow crosses a firewall, so this design is unmanageable in practice.
- Role-based zones. This is the textbook design, and its risk is low at about 0.135. However, the traffic in this network is dominated by cross-role flows (Web↔App, App↔DB, Client↔Web), so the role boundaries cut straight through the heaviest communication. Latency is close to the per-host-isolation level at about 0.945.
- Random zones. Even random assignment lands in a similar region. This shows that the number of zones matters less than which hosts end up together.
The annealed design reaches $J \approx 0.295$, well below every baseline, which sit between roughly 0.43 and 0.53. Risk falls by about 76% relative to the flat network, and latency is about 66% lower than full isolation.
What the optimizer discovered, panel (b) and the segment listing
The optimizer found a layout that mixes roles by traffic affinity.
- One segment holds the database tier together with three of the App servers. These are the hosts with the heaviest mutual traffic, so keeping them together removes the most expensive boundary crossings.
- Another segment groups the Web servers with the remaining App and Client hosts that talk to them.
- A third segment gathers the Clients with the Auth servers, which they query constantly.
- IoT devices are isolated together with one management host.
- One management host sits in a segment of its own, acting as a dedicated administrative enclave.
In the heatmap, the bright traffic blocks fall inside the cyan-bordered squares along the diagonal. Heavy flows stay inside segments, and only a thin trickle of low-volume traffic crosses the boundaries. The few remaining bright cells outside the diagonal are the flows that now need firewall rules, and they are exactly the ones the operations term kept to a minimum.
Convergence, panel (a)
The blue curve shows the objective of the current state. It starts high and noisy, because at high temperature $\tau$ the annealer accepts many uphill moves and explores widely. As $\tau$ falls geometrically, the curve calms down and tracks the best-so-far line. The yellow best-so-far curve drops in steps, and each step corresponds to the annealer escaping one basin for a better one. It flattens well before the final iteration, which indicates the schedule is long enough for this problem size.
How many segments? Panel (e)
Going from 1 to 3 segments, risk collapses quickly while latency and operating cost rise only modestly, because the optimizer can place tightly coupled hosts together. Beyond about five segments the curves flatten, and the weighted objective is minimized at five segments. More segments than that bring no benefit, since the extra boundaries would cut high-traffic pairs or add operating cost without reducing risk enough to compensate. The practical rule is that the right number of segments is driven by the traffic structure of the network, not by the number of roles on an org chart.
The Pareto frontier in 3D, panel (c)
Each dot is an optimized design for a different risk weight. Dots with a high risk weight (yellow) sit at low risk but higher latency and operating cost, and dots with a low risk weight (purple) sit at the opposite corner. The gold star marks the chosen design at $w_R = 0.5$. Every point on this surface is a defensible design, and the choice among them is a policy decision about how much latency and operating burden the organization accepts in exchange for containment.
The segmented topology in 3D, panel (d)
Each segment is a cluster on a ring. Node height encodes asset value and node size encodes exposure. The tall nodes (databases and authentication servers) are grouped away from the large nodes (clients and IoT devices). Red lines are the heavy flows that still cross boundaries, and green lines are the heavy flows contained inside a segment. There are far more green lines than red ones, which is the visual signature of a good segmentation: communication is local, and the paths an attacker could use are short and well separated from the high-value assets.
8. Takeaways
- Segmentation is an optimization problem. Role-based zoning is a reasonable starting point, but traffic-aware assignment can beat it substantially when real communication patterns cut across roles.
- The $O(1)$ incremental evaluation of the objective is what makes annealing practical, even with multiple restarts and parameter sweeps.
- The weights $w_R$, $w_L$ and $w_O$ make the policy trade-off explicit. Sweeping them gives decision-makers a frontier of options instead of a single number.
- The same framework extends naturally to real data. Replace $T$ with measured NetFlow or VPC flow-log volumes, $e_i$ with vulnerability-scan scores, and $v_i$ with business-impact ratings, and the optimizer will propose a segment map ready for review.














