300 KiB
300 KiB
In [1]:
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as ssIn [2]:
latency_distribution = ss.lognorm(s=2, scale=np.exp(3))
sample_count = 50_000
sizes = np.array([2, 3, 5, 10, 11, 21, 50, 100])
# Для графиков по числу участников генерируем запросы небольшими порциями.
def latency_batches(size):
batch_size = 5_000
for start in range(0, sample_count, batch_size):
rows = min(batch_size, sample_count - start)
yield latency_distribution.rvs(size=(rows, size))In [3]:
np.random.seed(111)
single_sample = latency_distribution.rvs(size=1_000_000)
plt.hist(single_sample, bins=100, range=(0, 200))
plt.xlabel('latency (ms)')
plt.ylabel('# samples')
plt.title('Latency histogram (0–200 ms)')
print(f'mean (ms) = {single_sample.mean():.4f}')
print(f'p95 (ms) = {np.quantile(single_sample, 0.95):.4f}')
print(f'p99 (ms) = {np.quantile(single_sample, 0.99):.4f}')mean (ms) = 148.1569 p95 (ms) = 535.7011 p99 (ms) = 2094.1641
In [4]:
ordered = np.sort(single_sample)
times = np.geomspace(1, np.quantile(ordered, 0.999), 300)
remaining = 100 * (ordered.size - np.searchsorted(ordered, times, side='right')) / ordered.size
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
ax.loglog(times, remaining, color='#102D69', linewidth=2)
for q, color in [(0.95, '#7030A0'), (0.99, '#A64716')]:
t = np.quantile(ordered, q)
ax.plot(t, 100 * (1 - q), 'o', color=color, label=f'p{q*100:.0f} = {t:.0f} мс')
ax.axvline(1000, color='gray', linestyle='--', label='1 секунда')
ax.set(xticks=[1, 10, 100, 1000, 10000], xticklabels=['1', '10', '100', '1 000', '10 000'],
yticks=[0.1, 1, 5, 10, 50, 100], yticklabels=['0,1', '1', '5', '10', '50', '100'],
xlabel='Время ожидания, мс', ylabel='Запросы, которые ещё ждут ответа, %',
title='Хвост распределения задержки одного запроса')
ax.grid(which='major', alpha=0.25)
ax.legend()
plt.show()
print(f'Дольше секунды: {100 * np.mean(single_sample > 1000):.2f}% запросов')Дольше секунды: 2.52% запросов
In [5]:
np.random.seed(112)
chains = [3, 5, 11]
plt.title(f'Latency histogram (chained requests)')
plt.xlabel('latency (ms)')
plt.ylabel('# samples')
for chain in chains:
print(f'Generating request chains of length {chain}.')
sample = latency_distribution.rvs(size=(sample_count, chain)).sum(axis=1)
plt.hist(sample, bins=100, range=(0, 2000), label=f'length = {chain}', alpha=0.5)
print(f'mean (ms) = {sample.mean():.4f}')
print(f'p95 (ms) = {np.quantile(sample, 0.95):.4f}')
print(f'p99 (ms) = {np.quantile(sample, 0.99):.4f}')
plt.legend(loc=0, fontsize=12)Out [5]:
Generating request chains of length 3. mean (ms) = 437.9722 p95 (ms) = 1559.4717 p99 (ms) = 4609.5809 Generating request chains of length 5. mean (ms) = 739.0999 p95 (ms) = 2462.0763 p99 (ms) = 6784.6518 Generating request chains of length 11. mean (ms) = 1627.5960 p95 (ms) = 4752.3845 p99 (ms) = 11328.7289
<matplotlib.legend.Legend at 0x158268578c0>
In [6]:
np.random.seed(112)
probs = []
for size in sizes:
fast_count = 0
for delays in latency_batches(size):
fast_count += np.count_nonzero(delays.sum(axis=1) < 1000)
probs.append(fast_count / sample_count)
plt.title('Probability of latency < 1s')
plt.ylabel('probability')
plt.xlabel('chain length')
plt.ylim(0, 1.01)
plt.plot(sizes, probs)Out [6]:
[<matplotlib.lines.Line2D at 0x158294b4d70>]
In [7]:
np.random.seed(113)
fanout = [3, 5, 11]
plt.title(f'Latency histogram (parallel requests)')
plt.xlabel('latency (ms)')
plt.ylabel('# samples')
for size in fanout:
print(f'Generating parallel requests made of {size} simple requests.')
sample = latency_distribution.rvs(size=(sample_count, size)).max(axis=1)
plt.hist(sample, bins=100, range=(0, 2000), label=f'fanout = {size}', alpha=0.5)
print(f'mean (ms) = {sample.mean():.4f}')
print(f'p95 (ms) = {np.quantile(sample, 0.95):.4f}')
print(f'p99 (ms) = {np.quantile(sample, 0.99):.4f}')
plt.legend(loc=0, fontsize=12)Out [7]:
Generating parallel requests made of 3 simple requests. mean (ms) = 380.6806 p95 (ms) = 1367.5032 p99 (ms) = 4484.1842 Generating parallel requests made of 5 simple requests. mean (ms) = 576.6353 p95 (ms) = 2008.6674 p99 (ms) = 6287.7535 Generating parallel requests made of 11 simple requests. mean (ms) = 1063.9695 p95 (ms) = 3663.3975 p99 (ms) = 10333.2724
<matplotlib.legend.Legend at 0x15829515010>
In [8]:
np.random.seed(113)
probs = []
for size in sizes:
fast_count = 0
for delays in latency_batches(size):
fast_count += np.count_nonzero(delays.max(axis=1) < 1000)
probs.append(fast_count / sample_count)
plt.title('Probability of latency < 1s')
plt.ylabel('probability')
plt.xlabel('fanout')
plt.ylim(0, 1.01)
plt.plot(sizes, probs, 'o-', label='Моделирование')
plt.plot(sizes, latency_distribution.cdf(1000) ** sizes, '--', label='Теория')
plt.legend()
plt.show()In [9]:
def majority_latency(latencies):
# Индекс с нуля: для 3 реплик ждём 2-й ответ, для 10 — 6-й.
k = latencies.shape[1] // 2
return np.partition(latencies, k, axis=1)[:, k]
np.random.seed(113)
fanout = [3, 5, 11]
plt.title(f'Latency histogram (quorum)')
plt.xlabel('latency (ms)')
plt.ylabel('# samples')
for size in fanout:
print(f'Generating quorums made of {size // 2 + 1}/{size} simple requests.')
sample = majority_latency(latency_distribution.rvs(size=(sample_count, size)))
plt.hist(sample, bins=100, range=(0, 2000), label=f'fanout = {size}', alpha=0.5)
print(f'mean (ms) = {sample.mean():.4f}')
print(f'p95 (ms) = {np.quantile(sample, 0.95):.4f}')
print(f'p99 (ms) = {np.quantile(sample, 0.99):.4f}')
plt.legend(loc=0, fontsize=12)Out [9]:
Generating quorums made of 2/3 simple requests. mean (ms) = 48.6348 p95 (ms) = 179.4922 p99 (ms) = 454.7443 Generating quorums made of 3/5 simple requests. mean (ms) = 35.7639 p95 (ms) = 117.4859 p99 (ms) = 247.0989 Generating quorums made of 6/11 simple requests. mean (ms) = 26.3333 p95 (ms) = 67.3473 p99 (ms) = 110.6553
<matplotlib.legend.Legend at 0x1582996f620>
In [10]:
np.random.seed(113)
probs = []
for size in sizes:
fast_count = 0
for delays in latency_batches(size):
fast_count += np.count_nonzero(majority_latency(delays) < 1000)
probs.append(fast_count / sample_count)
plt.title('Probability of latency < 1s')
plt.ylabel('probability')
plt.xlabel('fanout')
plt.ylim(0, 1.01)
plt.plot(sizes, probs)Out [10]:
[<matplotlib.lines.Line2D at 0x15829c98ad0>]
In [11]:
def hedge_results(primary, replica, cutoff):
replica_finish = cutoff + replica
duration = np.minimum(primary, replica_finish).max(axis=1)
sent = np.count_nonzero(primary > cutoff)
won = np.count_nonzero(replica_finish < primary)
return duration, sent, won
np.random.seed(114)
fanout = [3, 5, 11]
plt.title(f'Latency histogram (hedged parallel requests)')
plt.xlabel('latency (ms)')
plt.ylabel('# samples')
cutoff = latency_distribution.ppf(0.95)
for size in fanout:
print(f'Generating parallel requests made of {size} simple requests.')
sample = latency_distribution.rvs(size=(sample_count, size))
sample2 = latency_distribution.rvs(size=(sample_count, size))
sample, sent, won = hedge_results(sample, sample2, cutoff)
print(f'mean hedges sent per client request = {sent / sample.size:.3f}')
print(f'mean hedges won per client request = {won / sample.size:.3f}')
plt.hist(sample, bins=100, range=(0, 2000), label=f'fanout = {size}', alpha=0.5)
print(f'mean (ms) = {sample.mean():.4f}')
print(f'p95 (ms) = {np.quantile(sample, 0.95):.4f}')
print(f'p99 (ms) = {np.quantile(sample, 0.99):.4f}')
plt.legend(loc=0, fontsize=12)Out [11]:
Generating parallel requests made of 3 simple requests. mean hedges sent per client request = 0.150 mean hedges won per client request = 0.134 mean (ms) = 195.2841 p95 (ms) = 577.6429 p99 (ms) = 774.9734 Generating parallel requests made of 5 simple requests. mean hedges sent per client request = 0.247 mean hedges won per client request = 0.219 mean (ms) = 271.9866 p95 (ms) = 624.9013 p99 (ms) = 905.9897 Generating parallel requests made of 11 simple requests. mean hedges sent per client request = 0.550 mean hedges won per client request = 0.485 mean (ms) = 417.4257 p95 (ms) = 733.8383 p99 (ms) = 1172.4697
<matplotlib.legend.Legend at 0x1582b240c20>
In [12]:
np.random.seed(114)
probs = []
for size in sizes:
fast_count = 0
for primary in latency_batches(size):
replica = latency_distribution.rvs(size=primary.shape)
duration, _, _ = hedge_results(primary, replica, cutoff)
fast_count += np.count_nonzero(duration < 1000)
probs.append(fast_count / sample_count)
plt.title('Probability of latency < 1s')
plt.ylabel('probability')
plt.xlabel('fanout')
plt.ylim(0, 1.01)
plt.plot(sizes, probs)Out [12]:
[<matplotlib.lines.Line2D at 0x15829fd5be0>]
In [13]:
np.random.seed(114)
shard_count = 10
primary = latency_distribution.rvs(size=(sample_count, shard_count))
replica = latency_distribution.rvs(size=primary.shape)
strategies = [('Без дубля', np.inf),
('После p95', latency_distribution.ppf(0.95)),
('После p99', latency_distribution.ppf(0.99))]
print(f"{'Стратегия':<12}{'Порог, мс':>10}{'p99 поиска, мс':>16}{'> 1 с, %':>11}"
f"{'Отправлено / 100':>19}{'Выиграло / 100':>17}")
for label, delay in strategies:
duration, sent, won = hedge_results(primary, replica, delay)
threshold = f'{delay:.0f}' if np.isfinite(delay) else '—'
print(f'{label:<12}{threshold:>10}{np.quantile(duration, 0.99):>16.0f}'
f'{100 * np.mean(duration > 1000):>11.2f}'
f'{100 * sent / primary.size:>19.2f}{100 * won / primary.size:>17.2f}')Стратегия Порог, мс p99 поиска, мс > 1 с, % Отправлено / 100 Выиграло / 100 Без дубля — 9631 22.53 0.00 0.00 После p95 539 1093 1.38 4.96 4.41 После p99 2106 2322 22.53 0.99 0.95