Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Batch up outgoing read-receipts to reduce federation traffic. #4890

Merged
merged 2 commits into from
Mar 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/4890.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Batch up outgoing read-receipts to reduce federation traffic.
8 changes: 8 additions & 0 deletions docs/sample_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,14 @@ log_config: "CONFDIR/SERVERNAME.log.config"
#
#federation_rc_concurrent: 3

# Target outgoing federation transaction frequency for sending read-receipts,
# per-room.
#
# If we end up trying to send out more read-receipts, they will get buffered up
# into fewer transactions.
#
#federation_rr_transactions_per_room_per_second: 50



# Directory where uploaded images and attachments are stored.
Expand Down
12 changes: 12 additions & 0 deletions synapse/config/ratelimiting.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ def read_config(self, config):
self.federation_rc_reject_limit = config.get("federation_rc_reject_limit", 50)
self.federation_rc_concurrent = config.get("federation_rc_concurrent", 3)

self.federation_rr_transactions_per_room_per_second = config.get(
"federation_rr_transactions_per_room_per_second", 50,
)

def default_config(self, **kwargs):
return """\
## Ratelimiting ##
Expand Down Expand Up @@ -111,4 +115,12 @@ def default_config(self, **kwargs):
# single server
#
#federation_rc_concurrent: 3

# Target outgoing federation transaction frequency for sending read-receipts,
# per-room.
#
# If we end up trying to send out more read-receipts, they will get buffered up
# into fewer transactions.
#
#federation_rr_transactions_per_room_per_second: 50
"""
115 changes: 96 additions & 19 deletions synapse/federation/sender/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,26 @@ def __init__(self, hs):

self._processing_pending_presence = False

# map from room_id to a set of PerDestinationQueues which we believe are
# awaiting a call to flush_read_receipts_for_room. The presence of an entry
# here for a given room means that we are rate-limiting RR flushes to that room,
# and that there is a pending call to _flush_rrs_for_room in the system.
self._queues_awaiting_rr_flush_by_room = {
} # type: dict[str, set[PerDestinationQueue]]

self._rr_txn_interval_per_room_ms = (
1000.0 / hs.get_config().federation_rr_transactions_per_room_per_second
)

def _get_per_destination_queue(self, destination):
"""Get or create a PerDestinationQueue for the given destination

Args:
destination (str): server_name of remote server

Returns:
PerDestinationQueue
"""
queue = self._per_destination_queues.get(destination)
if not queue:
queue = PerDestinationQueue(self.hs, self._transaction_manager, destination)
Expand Down Expand Up @@ -250,33 +269,91 @@ def send_read_receipt(self, receipt):
Args:
receipt (synapse.types.ReadReceipt): receipt to be sent
"""

# Some background on the rate-limiting going on here.
#
# It turns out that if we attempt to send out RRs as soon as we get them from
# a client, then we end up trying to do several hundred Hz of federation
# transactions. (The number of transactions scales as O(N^2) on the size of a
# room, since in a large room we have both more RRs coming in, and more servers
# to send them to.)
#
# This leads to a lot of CPU load, and we end up getting behind. The solution
# currently adopted is as follows:
#
# The first receipt in a given room is sent out immediately, at time T0. Any
# further receipts are, in theory, batched up for N seconds, where N is calculated
# based on the number of servers in the room to achieve a transaction frequency
# of around 50Hz. So, for example, if there were 100 servers in the room, then
# N would be 100 / 50Hz = 2 seconds.
#
# Then, after T+N, we flush out any receipts that have accumulated, and restart
# the timer to flush out more receipts at T+2N, etc. If no receipts accumulate,
# we stop the cycle and go back to the start.
#
# However, in practice, it is often possible to flush out receipts earlier: in
# particular, if we are sending a transaction to a given server anyway (for
# example, because we have a PDU or a RR in another room to send), then we may
# as well send out all of the pending RRs for that server. So it may be that
# by the time we get to T+N, we don't actually have any RRs left to send out.
# Nevertheless we continue to buffer up RRs for the room in question until we
# reach the point that no RRs arrive between timer ticks.
#
# For even more background, see https://github.com/matrix-org/synapse/issues/4730.

room_id = receipt.room_id

# Work out which remote servers should be poked and poke them.
domains = yield self.state.get_current_hosts_in_room(receipt.room_id)
domains = yield self.state.get_current_hosts_in_room(room_id)
domains = [d for d in domains if d != self.server_name]
if not domains:
return

logger.debug("Sending receipt to: %r", domains)
queues_pending_flush = self._queues_awaiting_rr_flush_by_room.get(
room_id
)

content = {
receipt.room_id: {
receipt.receipt_type: {
receipt.user_id: {
"event_ids": receipt.event_ids,
"data": receipt.data,
},
},
},
}
key = (receipt.room_id, receipt.receipt_type, receipt.user_id)
# if there is no flush yet scheduled, we will send out these receipts with
# immediate flushes, and schedule the next flush for this room.
if queues_pending_flush is not None:
logger.debug("Queuing receipt for: %r", domains)
else:
logger.debug("Sending receipt to: %r", domains)
self._schedule_rr_flush_for_room(room_id, len(domains))

for domain in domains:
self.build_and_send_edu(
destination=domain,
edu_type="m.receipt",
content=content,
key=key,
)
queue = self._get_per_destination_queue(domain)
queue.queue_read_receipt(receipt)

# if there is already a RR flush pending for this room, then make sure this
# destination is registered for the flush
if queues_pending_flush is not None:
queues_pending_flush.add(queue)
else:
queue.flush_read_receipts_for_room(room_id)

def _schedule_rr_flush_for_room(self, room_id, n_domains):
# that is going to cause approximately len(domains) transactions, so now back
# off for that multiplied by RR_TXN_INTERVAL_PER_ROOM
backoff_ms = self._rr_txn_interval_per_room_ms * n_domains

logger.debug("Scheduling RR flush in %s in %d ms", room_id, backoff_ms)
self.clock.call_later(backoff_ms, self._flush_rrs_for_room, room_id)
self._queues_awaiting_rr_flush_by_room[room_id] = set()

def _flush_rrs_for_room(self, room_id):
queues = self._queues_awaiting_rr_flush_by_room.pop(room_id)
logger.debug("Flushing RRs in %s to %s", room_id, queues)

if not queues:
# no more RRs arrived for this room; we are done.
return

# schedule the next flush
self._schedule_rr_flush_for_room(room_id, len(queues))

for queue in queues:
queue.flush_read_receipts_for_room(room_id)

@logcontext.preserve_fn # the caller should not yield on this
@defer.inlineCallbacks
Expand Down
64 changes: 62 additions & 2 deletions synapse/federation/sender/per_destination_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,20 @@ def __init__(self, hs, transaction_manager, destination):
# destination
self._pending_presence = {} # type: dict[str, UserPresenceState]

# room_id -> receipt_type -> user_id -> receipt_dict
self._pending_rrs = {}
self._rrs_pending_flush = False

# stream_id of last successfully sent to-device message.
# NB: may be a long or an int.
self._last_device_stream_id = 0

# stream_id of last successfully sent device list update.
self._last_device_list_stream_id = 0

def __str__(self):
return "PerDestinationQueue[%s]" % self._destination

def pending_pdu_count(self):
return len(self._pending_pdus)

Expand Down Expand Up @@ -118,6 +125,30 @@ def send_presence(self, states):
})
self.attempt_new_transaction()

def queue_read_receipt(self, receipt):
"""Add a RR to the list to be sent. Doesn't start the transmission loop yet
(see flush_read_receipts_for_room)

Args:
receipt (synapse.api.receipt_info.ReceiptInfo): receipt to be queued
"""
self._pending_rrs.setdefault(
receipt.room_id, {},
).setdefault(
receipt.receipt_type, {}
)[receipt.user_id] = {
"event_ids": receipt.event_ids,
"data": receipt.data,
}

def flush_read_receipts_for_room(self, room_id):
# if we don't have any read-receipts for this room, it may be that we've already
# sent them out, so we don't need to flush.
if room_id not in self._pending_rrs:
return
self._rrs_pending_flush = True
self.attempt_new_transaction()

def send_keyed_edu(self, edu, key):
self._pending_edus_keyed[(edu.edu_type, key)] = edu
self.attempt_new_transaction()
Expand Down Expand Up @@ -183,10 +214,12 @@ def _transaction_transmission_loop(self):
# We can only include at most 50 PDUs per transactions
pending_pdus, self._pending_pdus = pending_pdus[:50], pending_pdus[50:]

pending_edus = self._pending_edus
pending_edus = []

pending_edus.extend(self._get_rr_edus(force_flush=False))

# We can only include at most 100 EDUs per transactions
pending_edus, self._pending_edus = pending_edus[:100], pending_edus[100:]
pending_edus.extend(self._pop_pending_edus(100 - len(pending_edus)))

pending_edus.extend(
self._pending_edus_keyed.values()
Expand Down Expand Up @@ -224,6 +257,11 @@ def _transaction_transmission_loop(self):
self._last_device_stream_id = device_stream_id
return

# if we've decided to send a transaction anyway, and we have room, we
# may as well send any pending RRs
if len(pending_edus) < 100:
pending_edus.extend(self._get_rr_edus(force_flush=True))

# END CRITICAL SECTION

success = yield self._transaction_manager.send_new_transaction(
Expand Down Expand Up @@ -285,6 +323,28 @@ def _transaction_transmission_loop(self):
# We want to be *very* sure we clear this after we stop processing
self.transmission_loop_running = False

def _get_rr_edus(self, force_flush):
if not self._pending_rrs:
return
if not force_flush and not self._rrs_pending_flush:
# not yet time for this lot
return

edu = Edu(
origin=self._server_name,
destination=self._destination,
edu_type="m.receipt",
content=self._pending_rrs,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit nervous about not limiting the number of receipts going in here tbh. Can we limit it to less than 100 at least?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess, though given it's a 3-level dict, that's not completely trivial. What are your concerns?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My concern is that we end up sending 100s of read receipts in a single transaction, causing the remote to fall over. It feels a bit weird to bother limiting EDUs if we end up circumventing that for read receipts.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the far end falls over because it has received too many RRs, we ought to spec a limit rather than trusting other servers not to DoS us.

I'd rather hope that we won't end up with that many RRs queued up. But ok, suppose we decide to limit the number of RRs in an EDU. Presumably you'd actually want me to limit the number in a transaction rather than just sending two edus with 100 RRs in each in a single transaction?

It just feels like a bunch of work that I'm not convinced is justified. It's certainly not a nit.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IRL conversation: it's not entirely clear what would be the right thing to do here. Let's just get it shipped

)
self._pending_rrs = {}
self._rrs_pending_flush = False
yield edu

def _pop_pending_edus(self, limit):
pending_edus = self._pending_edus
pending_edus, self._pending_edus = pending_edus[:limit], pending_edus[limit:]
return pending_edus

@defer.inlineCallbacks
def _get_new_device_messages(self):
last_device_stream_id = self._last_device_stream_id
Expand Down
2 changes: 1 addition & 1 deletion synapse/handlers/receipts.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def received_client_receipt(self, room_id, receipt_type, user_id,
if not is_new:
return

self.federation.send_read_receipt(receipt)
yield self.federation.send_read_receipt(receipt)
richvdh marked this conversation as resolved.
Show resolved Hide resolved

@defer.inlineCallbacks
def get_receipts_for_room(self, room_id, to_key):
Expand Down
Loading