Congestion control

Since C-Tor version 0.4.7, Tor uses RTT-based congestion control at the circuit level. While several algorithms were implemented and evaluated as part of Proposal 324, the deployed algorithm is based on TCP Vegas.

We use a ProtoVer of “FlowCtrl=2” to signal support by Exits for congestion control, as described in Exit negotiation. Onion services advertise support in their descriptors, as described in Onion Service Negotiation.

This document only specifies behavior. See Proposal 324 for background information, experimental tuning, glossary definitions, and supporting research.

Congestion Signals [CONGESTION_SIGNALS]

Tor uses two indicators for congestion on a circuit: when the RTT across the circuit changes, and when the local ORConn becomes blocked.

As an additional optimization, we could also use the ECN signal described in ideas/xxx-backward-ecn.txt, but this is not implemented.

RTT measurement using SENDMEs

Tor clients, exits, and onion services measure the current circuit RTT by measuring the amount of time between sending a RELAY_COMMAND_DATA cell that would trigger a SENDME from the other endpoint, and the arrival of that SENDME cell. This means that RTT is measured every 31 data cells, as specified via the cc_sendme_inc consensus parameter.

Circuits record the minimum and maximum RTT measurement, as well as a smoothed value of representing the current RTT.

N_EWMA Smoothing [N_EWMA_SMOOTHING]

RTT estimation requires smoothing, to reduce the effects of packet jitter.

This smoothing is performed using N_EWMA, which is an Exponential Moving Average with alpha = 2/(N+1):

  N_EWMA = RTT*2/(N+1) + N_EWMA_prev*(N-1)/(N+1)
         = (RTT*2 + N_EWMA_prev*(N-1))/(N+1)

The second line’s rearranged form MUST be used in order to ensure that rounding errors are handled in a consistent manner across implementations.

During Slow Start, N is set using consensus parameter cc_ewma_ss.

After Slow Start, N is the number of SENDME acks between congestion window updates, multiplied by the percentage specified in consensus parameter cc_ewma_cwnd_pct, and then capped at a max of cc_ewma_max, but always at least 2:

  N = MAX(MIN(CWND_UPDATE_RATE(cc)*cc_ewma_cwnd_pct/100, `cc_ewma_max`), 2);

During Slow Start, CWND_UPDATE_RATE is 1, because the algorithm evaluates the congestion window on every SENDME. After slow start, it becomes round(CWND/('cc_cwnd_inc_rate'*'cc_sendme_inc')), which spaces out those steady-state re-evaluations across a congestion window.

Monotonic Clock Heuristics [CLOCK_HEURISTICS]

The timestamps for RTT are measured using a microsecond monotonic clock API that provides a clock that only moves forward. However, depending on the underlying system clock, this may result in the same timestamp value being returned for long periods of time, which would result in RTT 0-values. The clock may also jump forward, resulting in abnormally large RTT values.

To guard against this, we perform a series of heuristic checks on the time delta measured by the RTT estimator. The congestion-control event counters are decremented before applying these checks, since the SENDME acknowledgment has still arrived. If the checks detect a stall or jump, we do not use the rejected value to update RTT or BDP and do not run the congestion-window update logic. We only decrement inflight to account for the acknowledged cells, and then stop processing that SENDME.

If the time delta is 0, that is always treated as a clock stall, the RTT is not used, the processing described above stops after the event-counter and inflight updates, and the clock-stall state is cached globally.

If the circuit does not yet have an EWMA RTT or it is still in Slow Start, then no further checks are performed, and the RTT is used.

If the circuit has stored an EWMA RTT and has exited Slow Start, then every SENDME ACK, the new candidate RTT is compared to the stored EWMA RTT. If the new RTT is 5000 times larger than the EWMA RTT, then the circuit does not record that estimate, and does not update BDP or the congestion control algorithms for that SENDME ack. If the new RTT is 5000 times smaller than the EWMA RTT, then the circuit uses the globally cached value from above (ie: it assumes the clock is stalled only if there was previously also a 0-delta RTT).

If both ratio checks pass, the globally cached clock stall state is set to false (no stall), and the RTT value is used.

ORConn block handling

Tor treats a blocked local OR connection for a circuit as congestion signal.

For origin circuits, this is determined by whether the next-hop channel is blocked. For exits and onion services, it is based on whether the previous-hop channel is blocked.

In C-Tor, a channel is considered blocked if the number of queued cells for that circuit’s channel reaches or exceeds the cellq_high consensus parameter. It remains blocked until the queue size drops below the cellq_low consensus parameter.

Arti considers a channel blocked when poll_ready on the channel’s chan_sender message sink returns Poll::Pending. This happens when the channel is saturated and has reached its CHANNEL_BUFFER_SIZE limit of queued cells, which is 128 by default. It remains blocked until the message sink is ready to accept more cells.

NOTE: This CHANNEL_BUFFER_SIZE limit, as well as its relation to congestion signal delivery, should be investigated during performance tuning of arti-relay.

The channel block/unblock state is not processed as an out-of-band event. Instead, it is sampled only when the endpoint processes an incoming SENDME. If that SENDME is the first one to observe a transition from unblocked to blocked, the implementation forces an immediate congestion-control re-evaluation for that same SENDME. In Slow Start, this causes Vegas to exit Slow Start immediately and clamp the congestion window to BDP + cc_vegas_gamma. In Steady State, it causes the normal Vegas update logic to run immediately, where the blocked channel is treated like a congestion signal and usually causes a cc_cwnd_inc decrease (unless the estimated queue is already above the cc_vegas_delta threshold, in which case the stronger delta response is used instead).

This immediate triggering happens only on the transition into the blocked state. If the channel remains blocked, later SENDMEs do not repeatedly force immediate updates just because it is still blocked. However, the persistent blocked state continues to act as a congestion signal whenever the normal Vegas update point is reached, so the congestion window can still be decreased again while the channel remains blocked.

Likewise, when a later SENDME is the first one to observe a transition from blocked to unblocked, the implementation again forces an immediate Vegas re-evaluation for that SENDME. This does not delay re-evaluation for a full congestion window. Instead, the channel is simply no longer treated as blocked for that update, so Vegas immediately falls back to its normal RTT/queue-based rules. Depending on the current queue estimate and whether the window is full, that immediate post-unblock update may decrease the congestion window further, leave it unchanged, or allow it to increase.

NOTE: C-Tor has an additional heuristic for the case where the internal monotonic clock has been completely stalled such that no EWMA RTT has ever been obtained for the circuit. If the local channel is also blocked, C-Tor reduces the effective BDP estimate by the queued-cell count, clipped at the minimum congestion window, and allows the normal Vegas logic to react to that queue despite the rejected RTT sample.

This exception can over-dampen the congestion window and is unlikely to be helpful. It is a C-Tor implementation heuristic, not required behavior. Implementations SHOULD instead follow the clock-stall handling above: update the event counters and inflight, but hold the congestion window unchanged. Arti does not apply this C-Tor exception.

Congestion Window Update Algorithms [CONTROL_ALGORITHMS]

Tor’s congestion window update is performed using rules based on TCP Vegas (original paper; excellent explainer).

TCP Vegas control algorithm estimates the queue lengths at relays by subtracting the current BDP estimate from the current congestion window. It defines threshold levels for queue length estimates that determine when it should lower or increase the congestion window, to keep queue lengths bounded.

BDP and Queue Estimation

Assuming that the current congestion window is at or above the current BDP, the bandwidth estimate is the current congestion window size divided by the RTT estimate:

   BWE = cwnd / RTT_current_ewma

The BDP estimate is computed by multiplying the Bandwidth estimate by the minimum circuit latency:

   BDP = BWE * RTT_min

Simplifying:

   BDP = cwnd * RTT_min / RTT_current_ewma

The RTT_min for this calculation comes from the minimum RTT_current_ewma seen in the lifetime of this circuit. If the congestion window falls to cc_cwnd_min after slow start, implementations MAY choose to reset RTT_min for use in this calculation to either the RTT_current_ewma, or a percentile-weighted average between RTT_min and RTT_current_ewma, specified by cc_rtt_reset_pct. This helps with escaping starvation conditions.

The net effect of this estimation is to correct for any overshoot of the cwnd over the actual BDP.

This estimate will obviously underestimate BDP if cwnd is below BDP. The TCP Vegas congestion window update rules compensate for this underestimate.

We experimented with various alternative BDP estimation options from the TCP literature. After much testing of various ways to compute BDP, we were still unable to do much better than the original cwnd estimator.

Assuming the BDP estimate is accurate, any amount by which the congestion window exceeds the BDP will cause data to queue.

Thus, Vegas estimates the queue use caused by congestion as:

   queue_use = cwnd - BDP

Tor Vegas: TCP Vegas with Limited Slow Start [TOR_VEGAS]

We use TCP Vegas, modified to take ORConn blocking into account, and some changes to reduce overshoot in the Tor scenario.

Compared to textbook Vegas, Tor also re-evaluates congestion more frequently during slow start, by checking conditions on every SENDME instead of only once per congestion window. To compensate for the additional overshoot risk this creates, we introduced Limited Slow Start based on RFC3742, and altered the Vegas update rules to damp overshoot when the circuit is only partially using its window.

Limited Slow Start

Limited Slow Start provides a cc_sscap_* parameter for each path length, which reduces the congestion window increment rate after it is crossed, as per the rules in RFC3742:

  rfc3742_ss_inc(cwnd):
    if cwnd <= cc_ss_cap_pathtype:
      # Below the cap, we increment as per cc_cwnd_inc_pct_ss percent:
      # In C-Tor integer math: ((cc_cwnd_inc_pct_ss * cc_sendme_inc) + 50) / 100
      return round(cc_cwnd_inc_pct_ss*cc_sendme_inc/100)
    else:
      # This returns an increment equivalent to RFC3742, rounded,
      # with a minimum of inc=1.
      # From RFC3742:
      #  K = int(cwnd/(0.5 max_ssthresh));
      #  inc = int(MSS/K);
      # In C-Tor integer math, this is implemented as:
      #  return MAX(((cc_sendme_inc * cc_ss_cap_pathtype) + cwnd) / (2 * cwnd), 1)
      return MAX(round((cc_sendme_inc*cc_ss_cap_pathtype)/(2*cwnd)), 1);

Partially Full CWND Update Handling

Note: Arti implements these heuristics exactly, but they should be revisted during arti-relay performance tuning.

During both Slow Start and Steady State, if the congestion window is not full, we never increase the congestion window, but can still decrease it, or exit slow start. This is done to avoid causing overshoot.

The original TCP Vegas addressed this problem by computing BDP and queue_use from inflight (instead of from cwnd), but we found that approach to have signficantly worse performance.

Because C-Tor is single-threaded, multiple SENDME acks may arrive during one processing loop, before edge connections resume reading. For this reason, we provide two heuristics to provide some slack in determining the full condition. The first is to allow a gap between inflight and cwnd, parameterized as cc_cwnd_full_gap multiples of cc_sendme_inc:

   cwnd_is_full(cwnd, inflight):
     if inflight + 'cc_cwnd_full_gap'*'cc_sendme_inc' >= cwnd:
       return true
     else
       return false

The second heuristic immediately resets the full state if it falls below cc_cwnd_full_minpct full:

   cwnd_is_nonfull(cwnd, inflight):
     if 100*inflight < 'cc_cwnd_full_minpct'*cwnd:
       return true
     else
       return false

This full status is cached once per cwnd if ‘cc_cwnd_full_per_cwnd=1’; otherwise it is cached once per cwnd update. These two helper functions determine the number of acks in each case:

   SENDME_PER_CWND(cwnd):
     return ((cwnd + 'cc_sendme_inc'/2)/'cc_sendme_inc')
   CWND_UPDATE_RATE(cwnd, in_slow_start):
     # In Slow Start, update every SENDME
     if in_slow_start:
       return 1
     else: # Otherwise, update as per the 'cc_inc_rate' (31)
       return ((cwnd + 'cc_cwnd_inc_rate'*'cc_sendme_inc'/2)
           / ('cc_cwnd_inc_rate'*'cc_sendme_inc'));

Shadow experimentation indicated that cc_cwnd_full_gap=2 and cc_cwnd_full_per_cwnd=0 minimizes queue overshoot, where as cc_cwnd_full_per_cwnd=1 and cc_cwnd_full_gap=1 is slightly better for performance. Since there may be a difference between Shadow and live, we leave this parmeterization in place.

Complete Tor Vegas Update Algorithm

Here is the complete pseudocode for TOR_VEGAS with RFC3742, which is run every time an endpoint receives a SENDME ack. All variables are scoped to the circuit, unless prefixed by an underscore (local), or in single quotes (consensus parameters):

Even though this routine runs once per SENDME, not every invocation causes a congestion-window change. Some work happens on every SENDME: the implementation decrements the event counters, applies the monotonic-clock heuristics, updates RTT and BDP estimates if the clock check passes, recomputes queue use, and samples whether the window appears full.

If the clock heuristics reject the RTT sample, processing for that SENDME stops after decrementing inflight and the event counters. Likewise, the cwnd_full state is sampled on every SENDME, but it is only cleared at the coarser cadence selected by cc_cwnd_full_per_cwnd: either once per full cwnd worth of SENDMEs, or once per congestion-window update interval.

The actual cwnd adjustment rules are gated more tightly. During slow start, Tor checks for exit conditions on every SENDME, but only increases cwnd when the window is currently considered full; slow start can also end immediately on a congestion signal, on the cc_ss_max cap, or when the RFC3742 increment falls to the steady-state floor.

After slow start, the normal Vegas alpha/beta/delta rules only run when next_cc_event reaches zero, which is normally about once per steady-state update interval rather than on every SENDME. As described in ORConn block handling, transitions into or out of the blocked state can also force an immediate re-evaluation on that SENDME, without waiting for a full cwnd’s worth of acks.

  # Decrement counters that signal either an update or cwnd event
  if next_cc_event:
    next_cc_event--
  if next_cwnd_event:
    next_cwnd_event--

  # Do not update anything if we detected a clock stall or jump,
  # as per [CLOCK_HEURISTICS]
  if clock_stalled_or_jumped:
    inflight -= 'cc_sendme_inc'
    cwnd = MIN(cwnd, 'cc_cwnd_max')
    return

  if BDP > cwnd:
    _queue_use = 0
  else:
    _queue_use = cwnd - BDP

  if cwnd_is_full(cwnd, inflight):
    cwnd_full = 1
  else if cwnd_is_nonfull(cwnd, inflight):
    cwnd_full = 0

  if in_slow_start:
    if _queue_use < 'cc_vegas_gamma' and not orconn_blocked:
      # Only increase cwnd if the cwnd is full
      if cwnd_full:
        _inc = rfc3742_ss_inc(cwnd);
        cwnd += _inc

        # If the RFC3742 increment drops below steady-state increment
        # over a full cwnd worth of acks, exit slow start.
        if _inc*SENDME_PER_CWND(cwnd) <= 'cc_cwnd_inc'*'cc_cwnd_inc_rate':
          in_slow_start = 0
    else: # Limit hit or blocked. Exit Slow start (even if cwnd not full)
      in_slow_start = 0
      cwnd = BDP + 'cc_vegas_gamma'

    # Provide an emergency hard-max on slow start:
    if cwnd >= 'cc_ss_max':
      cwnd = 'cc_ss_max'
      in_slow_start = 0
  else if next_cc_event == 0:
    if _queue_use > 'cc_vegas_delta':
      cwnd = BDP + 'cc_vegas_delta' - 'cc_cwnd_inc'
    elif _queue_use > cc_vegas_beta or orconn_blocked:
      cwnd -= 'cc_cwnd_inc'
    elif cwnd_full and _queue_use < 'cc_vegas_alpha':
      # Only increment if queue is low, *and* the cwnd is full
      cwnd += 'cc_cwnd_inc'

    cwnd = MAX(cwnd, 'cc_cwnd_min')

  # Specify next cwnd and cc update
  if next_cc_event == 0:
    next_cc_event = CWND_UPDATE_RATE(cwnd)
  if next_cwnd_event == 0:
    next_cwnd_event = SENDME_PER_CWND(cwnd)

  # Determine if we need to reset the cwnd_full state
  # (Parameterized)
  if 'cc_cwnd_full_per_cwnd' == 1:
    if next_cwnd_event == SENDME_PER_CWND(cwnd):
      cwnd_full = 0
  else:
    if next_cc_event == CWND_UPDATE_RATE(cwnd):
      cwnd_full = 0

  # Update acked cells
  inflight -= 'cc_sendme_inc'

  # Apply the global congestion-window maximum after processing.
  cwnd = MIN(cwnd, 'cc_cwnd_max')

Stream-Level Flow Control [FLOW_CONTROL]

Flow control provides what is known as “pushback” – the property that if one endpoint stops reading data, the other endpoint stops sending data. This prevents data from accumulating at points in the network, if it is not being read fast enough by an application. Because Tor streams can connect to many different applications and endpoints per circuit, it is important to provide the property that if only one endpoint edge connection is inactive, it does not stall the whole circuit, in case one of those endpoints is malfunctioning or malicious.

However, window-based stream flow control imposes a speed limit on individual streams. If the stream window size is below the circuit congestion window size, then it becomes the speed limit of a download.

Hence, when congestion control is enabled, we discard stream windows entirely, and instead use a buffer-based design that uses XON/XOFF to signal when this buffer is too large.

Design Goals

A good XON/XOFF flow control algorithm design should satisfy these goals:

  • Avoid flapping: Avoid rapid switching back and forth with XON/XOFF cells
  • Fast resumption: Resume to full speed rapidly after a temporary suspension (e.g., suspending a background wget download and resuming it).
  • Limit chatter: Rate limit the overall transmission frequency of advisory XON updates over the network.

XON/XOFF flow control systems don’t send any packets under normal conditions, but in the (rare) event that an edge connection is slower than the Tor circuit, they will become quite chatty, sending XON and XOFF repeatedly across the circuit.

To avoid this, the XON cell contains advisory rate information based on the rate at which that edge connection can write data while it has data to write. The other endpoint can rate limit sending data for that stream to the rate advertised in the XON, to avoid excessive XON/XOFF chatter and sub-optimal behavior.

Furthermore, by underestimating the initial advisory rate and then increasing it upon fully draining the queue, the algorithm is less likely to trigger subsequent queue buildups and XON/XOFF flapping.

Circuit SENDME and Queue Interactions

Each endpoint (client, Exit, or onion service) sends circuit-level SENDME acks for all circuit cells as soon as they are decrypted and recognized, but before delivery to their edge connections.

This means that if the edge connection is blocked because an application’s SOCKS connection or a destination site’s TCP connection is not reading, data will build up in a queue at that endpoint, specifically in its application-facing stream delivery buffer. This is the buffer whose occupancy the Tor implementation can directly observe and use for flow-control decisions. It does not include the operating system’s socket buffers, which are downstream of this buffer.

In C-Tor, this delivery buffer is the edge connection’s outbuf. In Arti, it is the buffer within the DataStream. Both implementations can have additional buffering in their proxy code and in the operating system, but that downstream buffering is outside the XOFF threshold.

Consensus parameters govern the length of this queue that determines when XON and XOFF cells are sent, as well as when advisory XON cells that contain rate information can be sent. These parameters are separate for the queue lengths of exits, and of clients/services.

The flow-control consensus parameters are expressed in relay-cell payload multiples, but supported relay-cell formats do not all have the same maximum payload size. Implementations convert them to byte thresholds as follows:

  • cc_xoff_client and cc_xoff_exit use RELAY_PAYLOAD_SIZE_MIN, currently 488 bytes. Using the minimum prevents XOFF sidechannel checks from assuming that a cell carried more application data than it could carry in some relay formats, which could otherwise cause false-positive early-cell or frequency violations.
  • cc_xon_rate uses RELAY_PAYLOAD_SIZE_MAX, currently 498 bytes, because it represents a number of fully packed payload cells.

Thus, equal numerical values for an XOFF parameter and cc_xon_rate produce different byte thresholds. Byte counters count the actual stream DATA payload bytes carried, so a partially filled DATA cell contributes only its actual payload length.

(Because clients and services will typically have localhost connections for their edges, these both will need similar buffering limits. Exits may have different properties, since their edges will be remote TCP connections.)

XON/XOFF Transmission Criteria

If the length of the application-facing stream delivery buffer exceeds the size provided in the appropriate client or exit XOFF consensus parameter, a RELAY_COMMAND_STREAM_XOFF will be sent, which instructs the other endpoint to stop sending from that edge connection.

NOTE In C-Tor, we start a grace period of 5 milliseconds (arbitrarily chosen), before sending the RELAY_COMMAND_STREAM_XOFF. This gives the mainloop a chance to flush the buffer to the edge connection’s socket. Arti’s implementation does not use a grace period. When the buffer limit is reached, a RELAY_COMMAND_STREAM_XOFF is immediately queued to be sent.

Additionally, Arti also uses the maximum of cc_xoff_client and cc_xoff_exit as its XOFF transmission threshold, regardless of the local endpoint type. This differs from C-Tor’s use of the parameter appropriate for its local endpoint type. Using the maximum avoids requiring Arti’s stream flow-control layer to know whether it is running for a client, onion service, or exit. It also ensures that, if these two parameters diverge in a future consensus, Arti does not send XOFF earlier than an endpoint using either role-specific threshold would expect. With the currently deployed equal parameter values, the two behaviors are equivalent.

Once the delivery buffer completely empties, a RELAY_COMMAND_STREAM_XON will be sent, which allows the other end to resume reading on that edge connection. This XON also indicates the EWMA rate of queue drain since the start of data accumulation.

Advisory XON cells are also sent whenever the edge connection’s drain rate changes by more than ‘cc_xon_change_pct’ percent compared to the previously sent XON cell’s value.

Edge bandwidth rate advertisement [XON_ADVISORY]

NOTE: This section contains heuristics specific to C-Tor, which is constrained by its single-threaded event loop. Arti’s implementation currently sets the N_EWMA rate to Unlimited without attempting to compute a drain rate limit. This is acceptable for clients. Arti-relay exits will need to determine appropriate heuristics for rate calculation and advertisement.

As noted above, the XON cell provides a field to indicate the N_EWMA rate which edge connections drain their outgoing buffers.

To compute the drain rate, we maintain a timestamp and a byte count of how many bytes were successfully drained onto the socket from the connection outbuf, to measure the time it takes to successfully drain a specific amount of data from the outbuf to the socket.

To make such a measurement, we start the timer by recording a timestamp as soon as data begins to accumulate in an empty outbuf. We also explicitly check if the buffer exceeds an expected burst limit (currently 32 cells, about 16KB), to account for the fact that bytes can silently accumulate before the socket unblocks and socket writes begin.

After cc_xon_rate payload cells (converted to bytes) have been successfully written to the socket, we compute the drain rate for that interval as the number of bytes successfully drained divided by the elapsed time since the timer started. We use N_EWMA to average this rate into a running EWMA average, with N specified by the consensus parameter cc_xon_ewma_cnt. Every EWMA update, the byte count is set to 0 and a new timestamp is recorded. In this way, the EWMA counter is averaging N drain rates over intervals of cc_xon_rate payloads each.

If the outbuf is non-empty, and we have sent an XON before, and the N_EWMA rate has changed more than cc_xon_change_pct since the last XON, we send an updated rate. Because the EWMA rate is only updated every cc_xon_rate payloads worth of bytes, such advisory XON updates cannot be sent more frequently than this, and should be sent much less often in practice.

This is sender-side behavior only. Receiver-side sidechannel validation is specified in Sidechannel mitigation, and is based on lifetime byte/cell counters rather than strict spacing between individual XONs.

When the outbuf completely drains to 0, data can still arrive on the stream and be immediately written to the local consumer without accumulating in the queue. When the outbuf has remained empty while cc_xon_rate payloads worth of data have arrived and been immediately written, we double the EWMA rate. We continue to double it while the outbuf remains empty, every cc_xon_rate payloads. The measurement timestamp is also un-set (cleared) to 0.

KNOWN LIMITATION: The doubling rule does not entirely prevent XON/XOFF flapping for a consistently slow reader. In C-Tor, the advertised rate can increase while the outbuf is temporarily empty, overshoot the reader’s sustained rate, and cause the outbuf to reach the XOFF threshold again. The 5 millisecond XOFF grace period mitigates event-loop and Conflux bursts, but does not resolve this sustained-rate estimation problem. Future implementations may first reduce the advertised rate and observe whether the buffer shrinks before sending XOFF, but the waiting interval and reduction rule are not yet specified.

When an XOFF is sent, the EWMA rate is reset to 0, to allow fresh calculation upon drain.

If a clock stall or jump is detected by the clock heuristics described above, we also clear the timestamp and byte count, but do not clear the running EWMA value.

NOTE: Because our timestamps are microseconds, we chose to compute and transmit both of these rates as 1000 byte/sec units, as this reduces the number of multiplications and divisions and avoids precision loss.

Oomkiller behavior

A malicious client can attempt to exhaust memory in an Exit’s outbufs, by ignoring XOFF and advisory XONs. Implementations MAY choose to close specific streams with outbufs that grow too large, but since the exit does not know with certainty the client’s congestion window, it is non-trivial to determine the exact upper limit a well-behaved client might send on a blocked stream.

Implementations MUST close the streams with the oldest chunks present in their outbufs, while under global memory pressure, until memory pressure is relieved.

Sidechannel mitigation

In order to mitigate DropMark-style attacks, both XOFF and advisory XON transmission must be restricted. Because DropMark attacks are most severe before data is sent, clients MUST reject an XOFF or XON received before they have sent any data on that stream.

A recipient MUST reject an XOFF if it has already received an XOFF on that stream without an intervening XON. In other words, consecutive XOFFs are a protocol violation.

Clients SHOULD additionally ensure that the first XOFF does not arrive before they have sent the appropriate XOFF limit of bytes on a stream (cc_xoff_exit for exits, cc_xoff_client for onions). Implementations MAY use a lower positive threshold for this receiver-side check in order to tolerate different views of the consensus or avoid requiring the flow-control layer to know the peer’s endpoint type, provided they retain the no-data check above and the lifetime-frequency check below. Arti uses such a permitted relaxation, as described below.

Clients also SHOULD ensure that the first advisory XON does not arrive before the minimum of the XOFF limit and cc_xon_rate payloads worth of bytes have been transmitted.

Clients SHOULD ensure that the total number of received advisory XONs does not exceed the total bytes of data sent, divided by the minimum of the XOFF limit and cc_xon_rate (in bytes).

Clients also SHOULD ensure that the total number of XOFFs does not exceed the total sent data divided by the XOFF limit.

For these rules, an advisory XON is an XON received when there is no outstanding XOFF. An XON received after an XOFF is a resuming XON: it permits the sender to resume and is not included in the advisory-XON count.

Implementations currently differ here. Arti applies the advisory-XON limits only to advisory XONs as defined above. It tracks whether the stream is paused by a previously accepted XOFF, and classifies an XON as resuming only while in that paused state. Accepting the resuming XON returns the stream to the sending state, so another XON is advisory unless another XOFF is accepted first. Because consecutive XOFFs are rejected and XOFFs have their own sidechannel limits, an endpoint cannot obtain an unbounded supply of exempt resuming XONs. This directly limits unsolicited cells while allowing the XON needed to resume after every valid XOFF without counting them towards unsolicited totals; therefore the Arti enforcement is the desirable behavior.

C-Tor instead includes every received XON, including resuming XONs, in its lifetime XON count and applies the same limit to that total. Because C-Tor does not enforce these limits (and instead only emits them for the vanguards addon to consume), it is not impacted by Arti’s more precise accounting behavior.

NOTE: Arti uses the permitted more permissive receiver-side limits described above:

  • Its XOFF limit is min(cc_xoff_client, cc_xoff_exit) / 2.
  • Its limit for the first advisory XON is the minimum of that relaxed XOFF limit and cc_xon_rate / 2.
  • Its lifetime advisory-XON frequency limit is cc_xon_rate / 2, without also taking the minimum with an XOFF parameter.

These checks use the receiver’s view of the consensus. The factor of two provides tolerance when the sender and receiver have consensuses with different parameter values, allowing the parameters to be changed incrementally without causing otherwise valid circuits to close. Taking the minimum of the two XOFF parameters also avoids needing to know the peer’s endpoint type, and remains conservative if a consensus update changes which XOFF parameter is smaller. These relaxations weaken the frequency bounds compared with C-Tor, but the checks still reject XON or XOFF cells received before any stream data and still bound their long-term frequency with respect to application data transmission.

These checks are performed against the lifetime counts of sent bytes and received XON/XOFF cells on the stream, rather than validating minimal spacing between each individual cell. This ensures endpoints do not reject valid XONs or XOFFs that happen to occasionally arrive back-to-back due to timing quirks, while still bounding the long-term rate.

To enforce these limits over time while mitigating history-building attacks, endpoints track the number of received XON and XOFF cells, as well as the total transmitted bytes. These variables are scaled down (halved) when the XON or XOFF count reaches 200, or when the transmitted bytes reach 10 MB. Early scaling limits the ability of an adversary to send spurious XON/XOFF cells after a large amount of unrestricted data is transmitted.

NOTE: The scaling thresholds above describe C-Tor, which uses bounded counters. Arti instead uses saturating 64-bit lifetime counters and does not scale them down. This avoids the additional state transitions and rounding involved in counter scaling, but does not provide C-Tor’s mitigation against building a large amount of history before sending spurious XON or XOFF cells.

Implementations SHOULD close the circuit if these limits are violated on the client-side, to detect and resist DropMark-style attacks.

Additionally, because edges no longer use stream SENDME windows, we alter the half-closed connection handling to be time based instead of data quantity based. Half-closed connections are allowed to receive data up to the larger value of the congestion control max_rtt field or the circuit build timeout (for onion service circuits, we use twice the circuit build timeout). Any data or relay cells after this point are considered invalid data on the circuit.

Recall that all of the dropped cell enforcement in C-Tor is performed by accounting data provided through the control port CIRC_BW fields, currently enforced only by using the vanguards addon.

The C-Tor implementation exposes all of these properties to CIRC_BW for vanguards to enforce, but does not enforce them itself. So violations of any of these limits do not cause circuit closure unless that addon is used (as with the rest of the dropped cell side channel handling in C-Tor).

Complete Stream Flow Control State Machine

This sender-side state machine represents the C-Tor implementation of Stream Flow Control, including its custom event-loop heuristics:

diagram

The receiver-side command state machine is shared by C-Tor and Arti:

diagram

The validation on each transition includes checking that congestion control was negotiated for the circuit, that the command belongs to the correct stream and hop, that its version and encoding are recognized, and that the sidechannel limits above are satisfied. An initial XON is an advisory XON and therefore uses the Sending to Sending transition.

Exit negotiation [EXIT_NEGOTIATION]

Similar to onion services, clients and exits will need to negotiate the decision to use congestion control, as well as a common value for cc_sendme_inc, for a given circuit.

When to negotiate

Clients decide to initiate a negotiation attempt for a circuit if the consensus lists a non-zero cc_alg parameter value, and the protover line for their chosen exit includes a value of 2 in the “FlowCtrl” field.

If the FlowCtrl=2 subprotocol is absent, a client MUST NOT attempt congestion-control negotiation. This restriction does not prohibit using ntorv3 for other purposes.

If cc_alg is absent or zero, a client SHOULD NOT attempt congestion-control negotiation. It MAY still use ntorv3 for other purposes.

If the protover and consensus conditions are met, clients SHOULD negotiate with the Exit if the circuit is to be used for exit stream activity. Clients MAY negotiate congestion control for one-hop circuits and internal circuits.

It’s not currently possible to negotiate anything with a CREATE_FAST handshake, however. Proposal 364 attempts to address this.

What to negotiate

Clients and exits need not agree on a specific congestion control algorithm, or any aspects of its behavior. Each endpoint’s management of its congestion window is independent. However, because the new algorithms no longer use stream SENDMEs or fixed window sizes, they cannot be used with an endpoint expecting the old behavior.

Additionally, each endpoint must agree on the the SENDME increment rate, in order to synchronize SENDME authentication and pacing.

For this reason, negotiation needs to establish a boolean: “use congestion control”, and an integer value for SENDME increment.

No other parameters need to be negotiated.

How to negotiate

Negotiation is performed by sending an ntorv3 onionskin, as specified in Proposal 332, to the Exit node. The encrypted payload contents from the clients are encoded as an extension field, as in the onion service INTRO1 cell:

  EXT_FIELD_TYPE:

    [01] -- Congestion Control Request.

As in the INTRO1 extension field, this field has zero payload length.

Its presence signifies that the client wants to use congestion control. The client MUST NOT set this field if this exit did not list “2” in the “FlowCtrl” version line. This does not prohibit using ntorv3 without this field. The client SHOULD NOT include this field if the consensus parameter cc_alg is 0.

The Exit MUST ignore any additional unknown extension fields.

The server’s encrypted ntorv3 reply payload is encoded as:

   EXT_FIELD_TYPE:

    [02] -- Congestion Control Response.

The Exit includes this extension only when the client requested congestion control and the Exit has congestion control enabled. If the response extension is absent, congestion control is disabled for the circuit.

The EXT_FIELD content payload is a single byte:

    sendme_inc        [1 byte]

The Exit MUST provide its current view of cc_sendme_inc in this payload. Exits SHOULD include this field only once.

The client MUST use the FIRST such field value, and ignore any duplicate field specifiers. The client MUST ignore any unknown additional fields.

Client checks

The client MUST reject any ntorv3 replies for non-ntorv3 onionskins.

The client MUST reject an ntorv3 reply with field EXT_FIELD_TYPE=02, if the client did not include EXT_FIELD_TYPE=01 in its handshake.

The client MUST reject a malformed response field, a zero sendme_inc, or a sendme_inc that differs from the client’s current cc_sendme_inc consensus parameter by more than +/- 1 in either direction. Since the field is an unsigned byte, its wire range is [1, 255]; the value 255 is acceptable only when it also passes the +/- 1 check.

If a client rejects a handshake, it MUST close the circuit.

Onion Service Negotiation [ONION_NEGOTIATION]

Onion service requires us to advertise the protocol version and congestion control parameters in a different way since the end points do not know each other like a client knows all the relays and what they support. Additionally, we cannot use ntorv3 for onion service negotiation, because it is not supported at all rendezvous and introduction points.

To address this, this is done in two parts. First, the service needs to advertise to the world that it supports congestion control, and its view of the current cc_sendme_inc consensus parameter. This is done through the flow-control onion service descriptor item.

Second, the client needs to inform the service that it wants to use congestion control on the rendezvous circuit. This is done through the encrypted CC_FIELD_REQUEST INTRODUCE extension.

Onion Service Descriptor

The flow-control item advertises the flow control protocol version in the encrypted section of the onion service descriptor:

  "flow-control" SP version-range SP sendme-inc NL

    The "version-range" value is the same as the protocol version FlowCtrl
    that relay advertises which is defined earlier in this proposal. The
    current value is "1-2".

    The "sendme-inc" value comes from the service's current cc_sendme_inc
    consensus parameter.

Clients MUST ignore additional unknown versions in “version-range”, and MUST ignore any additional values on this line.

Clients SHOULD use the highest value in “version-range” that they also support to govern their protocol choice for “FlowCtrl”. Congestion control as specified here requires that this mutually supported set include version 2.

If clients do not support any of the versions in “version-range”, they SHOULD reject the descriptor. (They MAY choose to ignore this line instead, but doing so means using the old fixed-window SENDME flow control, which will likely be bad for the network).

Clients that are able to parse this line and know the protocol version MUST validate that the “sendme-inc” value is nonzero and differs from the cc_sendme_inc in their current consensus by no more than +/- 1. If “sendme-inc” is not within this range, they MUST reject the descriptor.

If their consensus also lists a non-zero “cc_alg”, they MAY then send in the INTRODUCE1 cell congestion control request extension field, which is detailed in the next section.

A service should only advertise its flow control version if congestion control is enabled. It MUST remove this line if congestion control is disabled.

If the service observes a change in cc_sendme_inc consensus parameter since it last published its descriptor, it MUST immediately close its introduction points, and publish a new descriptor with the new “sendme-inc” value. The additional step of closing the introduction points ensures that no clients arrive using a cached descriptor, with the old “sendme-inc” value.

INTRODUCE cell extension

The CC_FIELD_REQUEST extension requests that the service use congestion control on the rendezvous circuit. It is encoded in the encrypted section of the INTRODUCE message, not the portion readable by the introduction point.

If used, it needs to be encoded within the ENCRYPTED section of the INTRODUCE1 cell defined in rend-spec-v3.txt section 3.3. The content is defined as follow:

  EXT_FIELD_TYPE:

    [01] -- Congestion Control Request.

This field has zero payload length. Its presence signifies that the client wants to use congestion control. The client MUST NOT include this field if the service did not list “2” in the “FlowCtrl” line in the descriptor. The client SHOULD NOT provide this field if the consensus parameter cc_alg is 0.

The service MUST ignore any unknown fields.

Protocol Flow

First, the client verifies that the descriptor’s “flow-control” line contains version 2 and that its “sendme-inc” value passes the validation above. The client configures its side of the rendezvous circuit using that descriptor “sendme-inc” value.

The client then includes the zero-length CC_FIELD_REQUEST in the encrypted section of its INTRODUCE1 message. The request does not repeat the protocol version or “sendme-inc” value. No congestion-control response extension is sent by the onion service.

When the service receives the request, it enables congestion control on its side of the rendezvous circuit using its current cc_sendme_inc value. Services keep this value synchronized with published descriptors by closing their introduction points and publishing a new descriptor when the consensus value changes, as specified above.

Circuit Behavior

If the extension is not found in the cell, the service MUST NOT use congestion control on the rendezvous circuit.

Clients MUST encode the request with a zero-length body. The extension carries no values for the service to validate; its presence alone requests congestion control.

Protocol format specifications [PROTOCOL_SPEC]

Circuit window handshake format

To communicate the currently seen cc_sendme_inc consensus parameter to the other endpoint, clients and exits use an ntorv3 onionskin extension field. This happens during the CREATE onionskin (or RELAY_COMMAND_EXTEND for Exits).

The client sends a zero-length extension in the encrypted portion of the handshake:

  EXT_FIELD_TYPE:

    [01] -- Congestion Control Request.

The server responds with an extension containing its view of cc_sendme_inc:

  EXT_FIELD_TYPE:

    [02] -- Congestion Control Response.

The EXT_FIELD content payload for the response is a single byte:

struct trn_extension_field_cc {
  u8 sendme_inc;
};

Clients MUST reject handshakes where sendme_inc is zero or differs from the current cc_sendme_inc consensus parameter by more than +/- 1. The field’s wire range is [1, 255].

XON/XOFF relay cell formats

The trunnel relay cell payload definitions for XON and XOFF are:

struct xoff_cell {
  u8 version IN [0x00];
}

struct xon_cell {
  u8 version IN [0x00];

  u32 kbps_ewma; // 1000 BYTES per second
}

Parties SHOULD treat XON or XOFF cells with unrecognized versions as a protocol violation.

In xon_cell, a zero value for kbps_ewma means that the stream’s rate is unlimited. Parties should therefore not send “0” to mean “do not send data”. A nonzero value is expressed in decimal kilobytes per second: one unit means 1000 bytes per second, not 1000 bits per second.

Before any XON is received, sending is unlimited unless it has been paused by an XOFF. An XOFF pauses sending but does not change the token bucket’s refill rate, capacity, or existing credit.

When an XON with a nonzero value is received, let R be that value multiplied by 1000 bytes per second. The implementation sets both the token bucket refill rate and its capacity (maximum burst) to R, so that the bucket can hold one second of advertised traffic. The implementation preserves the bucket’s existing credit or debt when applying the new configuration, except that credit above the new capacity is discarded. Increasing the rate or capacity does not by itself grant additional credit. Tokens are consumed while reading from the local edge connection and packaging that data onto the circuit.

An XON with a zero value changes the refill rate and capacity to their implementation maximums, effectively removing the rate limit. It otherwise uses the same credit-preserving adjustment rule.

NOTE: C-Tor implements the credit-preserving behavior above. Arti uses the same one-second burst and preserves credit across ordinary XON rate changes. However, Arti currently represents XOFF by changing the rate and capacity to zero, which discards all existing credit. It therefore resumes from zero credit after the following XON.

7.3. Onion Service formats

To signal support for congestion control in an onion service, the service adds a new flow-control item to its encrypted descriptor:

  "flow-control" SP version-range SP sendme-inc NL

The version-range represents the FlowCtrl version (currently “1-2”), and sendme-inc is the service’s current cc_sendme_inc consensus parameter.

Clients signal their desire to use congestion control in the ENCRYPTED section of the INTRODUCE1 cell via a zero-length CC_FIELD_REQUEST extension:

  EXT_FIELD_TYPE:

    [01] -- Congestion Control Request.

Protocol Version format

Support for this specification is signaled via the FlowCtrl=2 protocol version. Relays that support congestion control MUST include this in their descriptor’s protocol versions.

The FlowCtrl protocol version range is also included in the onion service descriptor’s flow-control line, as detailed above.

Consensus Parameters [CONSENSUS_PARAMETERS]

Parameters common to all algorithms

These are sorted in order of importance to tune, most important first.

  • cc_alg:

    • Description: Specifies which congestion control algorithm clients should use, as an integer.
    • Range: 0 or 2 (0=fixed windows, 2=Vegas)
    • Default: 2
    • Tuning Values: 2
    • Tuning Notes: These algorithms need to be tested against percentages of current fixed alg client competition, in Shadow. Their optimal parameter values, and even the optimal algorithm itself, will likely depend upon how much fixed sendme traffic is in competition. See the algorithm-specific parameters for additional tuning notes. As of Tor 0.4.8, Vegas is the default algorithm, and support for algorithms 1 (Westwood) and 3 (NOLA) have been removed.
    • Shadow Tuning Results: Westwood exhibited responsiveness problems, drift, and overshoot. NOLA exhibited ack compression resulting in over-estimating the BDP. Vegas, when tuned properly, kept queues low and throughput high, but even.
  • cc_bwe_min:

    • Description: The minimum number of SENDME acks to average over in order to estimate bandwidth (and thus BDP).
    • Range: [2, 20]
    • Default: 5
    • Tuning Values: 4-10
    • Tuning Notes: The lower this value is, the sooner we can get an estimate of the true BDP of a circuit. Low values may lead to massive over-estimation, due to ack compression. However, if this value is above the number of acks that fit in cc_cwnd_init, then we won’t get a BDP estimate within the first use of the circuit. Additionally, if this value is above the number of acks that fit in cc_cwnd_min, we may not be able to estimate BDP when the congestion window is small. If we need small congestion windows, we should also lower cc_sendme_inc, which will get us more frequent acks with less data.
    • Shadow Tuning Results: Regarless of how high this was set, there were still cases where queues built up, causing BDP over-estimation. As a result, we disable use of the BDP estimator, and only use the Vegas CWND estimator.
  • cc_sendme_inc:

    • Description: Specifies how many cells a SENDME acks.
    • Range: [1, 254]
    • Default: 31
    • Tuning Values: 25,33,50
    • Tuning Notes: Decreasing this increases overhead, but also increases BDP estimation accuracy. Since we only use circuit-level SENDMEs, and the old code sent SENDMEs at both every 50 cells, and every 100, we can set this as low as 33 to have the same amount of overhead.
    • Shadow Tuning Results: This was optimal at 31-32 cells, which is also the number of cells that fit in a TLS frame. Much of the rest of Tor has processing values at 32 cells, as well.
    • Consensus Update Notes: This value MUST only be changed by +/- 1, every 4 hours. If greater changes are needed, they MUST be spread out over multiple consensus updates.
  • cc_cwnd_init:

    • Description: Initial congestion window for new congestion control Tor clients. This can be set much higher than TCP, since actual TCP to the guard will prevent buffer bloat issues at local routers.
    • Range: [31, 10000]
    • Default: 124
    • Tuning Values: 150,200,250,500
    • Tuning Notes: Higher initial congestion windows allow the algorithms to measure initial BDP more accurately, but will lead to queue bursts and latency. Ultimately, the ICW should be set to approximately ‘cc_bwe_min’*‘cc_sendme_inc’, but the presence of competing fixed window clients may require higher values.
    • Shadow Tuning Results: Setting this too high caused excessive cell queues at relays. 4*31 ended up being a sweet spot.
    • Consensus Update Notes: This value must never be set below cc_sendme_inc.
  • cc_cwnd_min:

    • Description: The minimum allowed cwnd.
    • Range: [31, 1000]
    • Default: 124
    • Tuning Values: 100, 150, 200
    • Tuning Notes: If the cwnd falls below cc_sendme_inc, connections can’t send enough data to get any acks, and will stall. If it falls below cc_bwe_mincc_sendme_inc, connections can’t use SENDME BDP estimates. Likely we want to set this around cc_bwe_mincc_sendme_inc, but no lower than cc_sendme_inc.
    • Shadow Tuning Results: The current source default sets this to the initial congestion window, or 124 cells.
    • Consensus Update Notes: This value must never be set below cc_sendme_inc.
  • cc_cwnd_max:

    • Description: The maximum allowed cwnd.
    • Range: [500, INT32_MAX]
    • Default: INT32_MAX
    • Tuning Values: 5000, 10000, 20000
    • Tuning Notes: If cc_bwe_min is set too low, the BDP estimator may over-estimate the congestion window in the presence of large queues, due to SENDME ack compression. Once all clients have upgraded to congestion control, queues large enough to cause ack compression should become rare. This parameter exists primarily to verify this in Shadow, but we preserve it as a consensus parameter for emergency use in the live network, as well.
    • Shadow Tuning Results: We kept this at INT32_MAX.
  • cellq_high:

    • Description: The number of queued cells on a circuit’s channel at which the channel is considered blocked.
    • Range: [1, 1000]
    • Default: 256
  • cellq_low:

    • Description: The number of queued cells on a circuit’s channel below which the channel is considered unblocked again.
    • Range: [1, 1000]
    • Default: 10
  • orconn_high:

    • Description: The OR connection outbuf high watermark, in bytes, at which Tor stops accepting more cells into the outbuf.
    • Range: [CELL_PAYLOAD_SIZE, INT32_MAX]
    • Default: 32768
  • orconn_low:

    • Description: The OR connection outbuf low watermark, in bytes, below which Tor resumes accepting more cells into the outbuf.
    • Range: [CELL_PAYLOAD_SIZE, INT32_MAX]
    • Default: 16384
  • circwindow:

    • Description: Initial congestion window for legacy Tor clients.
    • Range: [100, 1000]
    • Default: 1000
    • Tuning Values: 100,200,500,1000
    • Tuning Notes: If the above congestion algorithms are not optimal until an unreasonably high percentge of clients upgrade, we can reduce the performance of ossified legacy clients by reducing their circuit windows. This will allow old clients to continue to operate without impacting optimal network behavior.
  • cc_cwnd_inc_rate:

    • Description: The target number of steady-state congestion window re-evaluations per congestion window’s worth of acknowledged data. A value of 1 causes approximately one Vegas update per cwnd; larger values cause more frequent steady-state updates.
    • Range: [1, 250]
    • Default: 31
    • Tuning Values: 1,2,5,10
    • Tuning Notes: Congestion control theory says that the congestion window should only be updated once every cwnd worth of packets. Tor allows more frequent steady-state Vegas updates by setting this above 1, which also reduces the post-slow-start EWMA smoothing window because CWND_UPDATE_RATE feeds into that calculation. This parameter does not change the fact that slow start itself evaluates on every SENDME.
    • Shadow Tuning Results: Higher values caused more frequent steady-state re-evaluation and were suboptimal for performance in Shadow. The current source default is 31, which with the default cc_sendme_inc of 31 means Tor re-evaluates roughly once per SENDME after slow start.
  • cc_ewma_cwnd_pct:

    • Description: This specifies the N in N-EWMA smoothing of RTT and BDP estimation, as a percent of the number of SENDME acks in a congestion window. It allows us to average these RTT values over a percentage of the congestion window, capped by ‘cc_ewma_max’ below, and specified in the N_EWMA smoothing section above.
    • Range: [1, 255]
    • Default: 50
    • Tuning Values: 25,50,100
    • Tuning Notes: Smoothing our estimates reduces the effects of ack compression and other ephemeral network hiccups; changing this much is unlikely to have a huge impact on performance.
    • Shadow Tuning Results: Setting this to 50 seemed to reduce cell queues, but this may also have impacted performance.
  • cc_ewma_max:

    • Description: This specifies the max N in N_EWMA smoothing of RTT and BDP estimation. It allows us to place a cap on the N of EWMA smoothing, as specified in the N_EWMA smoothing section above.
    • Range: [2, INT32_MAX]
    • Default: 10
    • Tuning Values: 10, 20
    • Shadow Tuning Results: We ended up needing this to make Vegas more responsive to congestion, to avoid overloading slow relays. Values of 10 or 20 were best.
  • cc_ewma_ss:

    • Description: This specifies the N in N_EWMA smoothing of RTT during Slow Start.
    • Range: [2, INT32_MAX]
    • Default: 2
    • Tuning Values: 2,4
    • Shadow Tuning Results: Setting this to 2 helped reduce overshoot during Slow Start.
  • cc_rtt_reset_pct:

    • Description: Describes a percentile average between RTT_min and RTT_current_ewma, for use to reset RTT_min, when the congestion window hits cwnd_min.
    • Range: [0, 100]
    • Default: 100
    • Shadow Tuning Results: cwnd_min is not hit in Shadow simulations, but it can be hit on the live network while under DoS conditions, and with cheaters.
  • cc_cwnd_inc:

    • Description: How much to increment the congestion window at each steady-state congestion-window update.
    • Range: [1, 1000]
    • Default: 1
    • Tuning Values: 25,50,100
    • Tuning Notes: We are unlikely to need to tune this much, but it might be worth trying a couple values.
    • Shadow Tuning Results: Increasing this negatively impacted performance. The current source default keeps this at 1 cell.
  • cc_cwnd_inc_pct_ss:

    • Description: Percentage of the current congestion window to increment by during slow start, every cwnd.
    • Range: [1, 500]
    • Default: 100
    • Tuning Values: 50,100,200
    • Tuning Notes: On the current live network, the algorithms tended to exit slow start early, so we did not exercise this much. This may not be the case in Shadow, or once clients upgrade to the new algorithms.
    • Shadow Tuning Results: Historical tuning explored values in the 50-100 range. The current source default is 100.

Vegas Parameters

  • cc_vegas_alpha_{exit,onion,sbws}, cc_vegas_beta_{exit,onion,sbws}, cc_vegas_gamma_{exit,onion,sbws}, cc_vegas_delta_{exit,onion,sbws}:

    • Description: These parameters govern the number of cells that TOR_VEGAS can detect in queue before reacting.

    • Range: [0, 1000] (except delta, which has max of INT32_MAX)

    • Defaults:

      # TLS_RECORD_MAX_CELLS = 31; OUTBUF_CELLS = 62
      cc_vegas_alpha_sbws = 93
      cc_vegas_beta_sbws = 155
      cc_vegas_gamma_sbws = 124
      cc_vegas_delta_sbws = 248
      cc_vegas_alpha_exit = 186
      cc_vegas_beta_exit = 248
      cc_vegas_gamma_exit = 186
      cc_vegas_delta_exit = 310
      cc_vegas_alpha_onion = 186
      cc_vegas_beta_onion = 372
      cc_vegas_gamma_onion = 248
      cc_vegas_delta_onion = 434
      
    • Consensus Value:

      cc_vegas_alpha_sbws = 186
      cc_vegas_beta_sbws = 248
      cc_vegas_gamma_sbws = 186
      cc_vegas_delta_sbws = 310
      
    • Tuning Notes: The amount of queued cells that Vegas should tolerate is heavily dependent upon competing congestion control algorithms. The specified defaults are necessary to compete against current fixed SENDME traffic, but are much larger than necessary otherwise. These values also need a large-ish range between alpha and beta, to allow some degree of variance in traffic, as seen in prior Vegas tuning work. The tuning of these parameters happened in two implementation tickets. The onion service parameters were set on the basis that they should increase the queue until as much queue delay as Exits, but tolerate up to 6 hops of outbuf delay. Lack of visibility into onion service congestion window on the live network prevented confirming this.

    • Shadow Tuning Results: We found that the best values for 3-hop Exit circuits was to set alpha and gamma to the size of the outbufs times the number of hops. Beta is set to one TLS record/sendme_inc above this value.

  • cc_sscap_{exit,onion,sbws}:

    • Description: These parameters describe the RFC3742 ‘cap’, after which congestion window increments are reduced. INT32_MAX disables RFC3742.
    • Range: [100, INT32_MAX]
    • Defaults: sbws: 400, exit: 600, onion: 475
    • Consensus Value: sbws: 600
    • Shadow Tuning Results: We picked these defaults based on the average congestion window seen in Shadow sims for exits and onion service circuits.
  • cc_ss_max:

    • Description: This parameter provides a hard-max on the congestion window in slow start.
    • Range: [500, INT32_MAX]
    • Default: 5000
    • Shadow Tuning Results: The largest congestion window seen in Shadow is ~3000, so this was set as a safety valve above that.
  • cc_cwnd_full_gap:

    • Description: This parameter defines the integer number of ‘cc_sendme_inc’ multiples of gap allowed between inflight and cwnd, to still declare the cwnd full.
    • Range: [0, INT16_MAX]
    • Default: 4
    • Shadow Tuning Results: Low values resulted in a slight loss of performance, and increased variance in throughput. Setting this at 4 seemed to achieve a good balance betwen throughput and queue overshoot.
  • cc_cwnd_full_minpct:

    • Description: This parameter defines a low watermark in percent. If inflight falls below this percent of cwnd, the congestion window is immediately declared non-full.
    • Range: [0, 100]
    • Default: 25
  • cc_cwnd_full_per_cwnd:

    • Description: This parameter governs how often a cwnd must be full, in order to allow congestion window increase. If it is 1, then the cwnd only needs to be full once per cwnd worth of acks. If it is 0, then it must be full once every cwnd update (ie: every SENDME).
    • Range: [0, 1]
    • Default: 1
    • Shadow Tuning Results: A value of 0 resulted in a slight loss of performance, and increased variance in throughput. The optimal number here likely depends on edgeconn inbuf size, edgeconn kernel buffer size, and eventloop behavior.

Flow Control Parameters

As with previous sections, the parameters in this section are sorted with the parameters that are most important to tune, first.

These parameters have been tuned using onion services. The defaults are believed to be good.

  • cc_xoff_client, cc_xoff_exit:

    • Description: Specifies the outbuf length, in relay cell multiples, before we send an XOFF.
    • Range: [1, 10000]
    • Default: 500
    • Tuning Values: 500, 1000
    • Tuning Notes: This threshold plus the sender’s cwnd must be greater than the cc_xon_rate value, or a rate cannot be computed. Unfortunately, unless it is sent, the receiver does not know the cwnd. Therefore, this value should always be higher than cc_xon_rate minus the default ‘cc_cwnd_min’ (124) minus the xon threshhold value (0).
  • cc_xon_rate:

    • Description: Specifies how many full packed cells of bytes must arrive before we can compute a rate, as well as how often we can send XONs.
    • Range: [1, 5000]
    • Default: 500
    • Tuning Values: 500, 1000
    • Tuning Notes: Setting this high will prevent excessive XONs, as well as reduce side channel potential, but it will delay response to queuing and will hinder our ability to detect rate changes. However, low values will also reduce our ability to accurately measure drain rate. This value should always be lower than ‘cc_xoff_*’ + ‘cc_cwnd_min’, so that a rate can be computed solely from the outbuf plus inflight data.
  • cc_xon_change_pct:

    • Description: Specifies how much the edge drain rate can change before we send another advisory cell.
    • Range: [1, 99]
    • Default: 25
    • Tuning values: 25, 50, 75
    • Tuning Notes: Sending advisory updates due to a rate change may help us avoid hitting the XOFF limit, but it may also not help much unless we are already above the advise limit.
  • cc_xon_ewma_cnt:

    • Description: Specifies the N in the N_EWMA of rates.
    • Range: [2, 100]
    • Default: 2
    • Tuning values: 2, 3, 5
    • Tuning Notes: Setting this higher will smooth over changes in the rate field, and thus avoid XONs, but will reduce our reactivity to rate changes.

Managing consensus updates

The pedantic reader will note that a rogue consensus can cause all clients to decide to close circuits by changing ‘cc_sendme_inc’ by a large margin.

As a matter of policy, the directory authorities MUST NOT change ‘cc_sendme_inc’ by more than +/- 1.

In Shadow simulation, the optimal ‘cc_sendme_inc’ value to be ~31 cells, or one (1) TLS record worth of cells. We do not expect to change this value significantly.

Arti’s receiver-side checks use half of its current cc_xon_rate and XOFF limits, as described above. To preserve interoperability between endpoints using different, concurrently valid consensuses, directory authorities MUST ensure that, for each of cc_xon_rate, cc_xoff_client, and cc_xoff_exit, the largest value and smallest value across consensuses that can be used at the same time differ by no more than a factor of two. This restriction applies to both increases and decreases, since either endpoint may obtain the newer consensus first. In particular, a receiver using a larger value can otherwise reject XON or XOFF cells sent by a peer that is still using a smaller value.

This factor-of-two rule does not protect a newly bootstrapping client whose built-in defaults differ substantially from the current consensus. At present, this is not an issue for one-hop directory circuits because CREATE_FAST cannot negotiate congestion control. If Proposal 364 enables congestion control on one-hop bootstrap circuits, a client without a live consensus MUST still reject XON or XOFF before sending any stream data and MUST reject consecutive XOFFs, but MUST NOT apply the consensus-parameter-based early-cell or frequency limits on those bootstrap circuits. Once the client has a live consensus, it applies the normal checks to newly created circuits.