General Knowledge
Dense Switch Statements
Dense switch statements on primitives refer to switch-case constructs in programming languages like Java, C, and C++ that are used to handle multiple cases of a single primitive variable (like an integer, char, etc.). These switch statements can be optimized by the compiler for better performance, especially when the cases are dense (i.e., the case values are close together).
Compiler Optimization for Dense Switch Statements
When the cases in a switch statement are dense, modern compilers often optimize the code to use a jump table (address offsets), which provides O(1) time complexity for selecting the correct case.
Second-level Latency
It refers to the delay encountered when processing or accessing data that is not immediately available in the primary (first-level) cache or memory, but requires accessing a secondary source or cache.
NLB (Network-layer Load Balancer) vs ALB (Application-layer Load Balancer)
NLB is good for applications that require ultra-low latency, while ALB is good for advanced routing based on HTTP/HTTPS request content.
Manifest
It’s a special file within a JAR that contains metadata about the files packaged in the archive. The manifest file is named MANIFEST.MF and is located in the META-INF directory of the JAR file. It provides information such as versioning, main class definition, classpath entries and other configurations that help the JVM understand how to execute the JAR.
Shadowed Jar
It contains not only your compiled application code but also all its dependencies (libraries, frameworks, etc.) bundled into a single archive. This is particularly useful for deploying standalone Java applications, as it ensures that all necessary dependencies are included, so you don’t have to manage them separately on the classpath. The problem with Shadowed Jars is that its dependencies’ versions might conflict with the project’s dependencies’ versions. Therefore, the general of thumb is not to import shadowed jars as dependencies but the standalone application only. Its dependencies are imported separately, so there is only 1 single source of truth for the version of each library.
Mocking the dropping of leased line connections
- Append the following to the end of the file
/etc/pf.conf - It’s the configuration file for Packet Filter, a firewall and network address translation (NAT) system used primarily on OpenBSD.
block drop proto tcp from any to localhost port 20735
block drop proto tcp from any to localhost port 20734
block drop proto tcp from any to localhost port 20744
block drop proto tcp from any to localhost port 20745sudo pfctl -e -f /etc/pf.confto apply changessudo pfctl -dto recover- Monitor connection from host to remote:
netstat -an | grep <port>
CLOSED: Initial state of both client and serverSYN_SENT: After client sends a SYN packetSYN_RECEIVED: After server receives SYN.ESTABLISHED: After client and server receives ACK.FIN_WAIT_1: After Initiator sends FIN.CLOSE_WAIT: After receiver receives FIN.FIN_WAIT_2: After initiatorLAST_ACK: After receiver sends FINTIME_WAITis for the initiator to have enough time to resend ACK (in case ACK is lost for whatever reason)CLOSED: AfterTIME_WAITexpires for initiator and after receiver receives ACK.
TCP keep-alive
When 2 hosts are connected over TCP/IP, TCP Keepalive Packets can be used to determine if the connection is still valid, and terminate it if needed.
TLS/SSL (v1.3)
Client Server
| |
| ClientHello |
|--------------------------------------------------->|
| |
| ServerHello |
| EncryptedExtensions
| [Certificate]*
| [CertificateVerify]*
| Finished
|<---------------------------------------------------|
| |
| Finished |
|--------------------------------------------------->|
| |
Secure Communication Established-Djavax.net.debug=ssl,handshake
Virtual Memory
Another note: Windows separates virtual memory allocation into separate MEM_RESERVE and MEM_COMMIT calls. MEM_RESERVE reserves address space and MEM_COMMIT commits it to physical memory. That does not mean that physical memory is actually allocated when you MEM_COMMIT, the physical memory is still not allocated until you actually touch the pages. But MEM_COMMIT reserves memory in the page file, and if you try to commit more memory than you have in your page file, MEM_COMMIT will fail. So on Windows, you probably don’t want to MEM_COMMIT the entire lookup table (because you only have a limited size page file). Instead, you want to MEM_RESERVE the whole table in the beginning and then just MEM_COMMIT the range of the table that you actually use.
In contrast, Linux allows overcommitting — i.e., you can commit more memory than the size of your page file. For this reason, Linux doesn’t need separate reserve/commit operations which makes the virtual memory a lot simpler to use.
Time/Clock
- RDTSC (“Read Time-Stamp Counter) is an x86 assembly instruction that reads a high-resolution, CPU-cycle counter.
NTP (Network Time Protocol)
- Uses the intersection algorithm, which is a modified form of Marzullo’s algorithm
- Polls NTP servers for time, and choose the intersection point which falls in the majority of these time ranges, that gives an accurate time
Slewing vs Jumping time
https://stackoverflow.com/questions/33746324/ntp-questions-slewing-versus-jumping-the-time
The word “Native”
Compiled into machine code and exposes a C-compatible interface (ABI)
Measuring latency
- Most of the tools that capture response times, report 99 percentile latency of every 30 sec duration. For example prometheus metrics are scraped every minute. But the real thing to look at is the Max response time.
- Gatling fixed the co-ordinated omission problem. Most of the other tools like Jmeter, etc still have this problem. So use Gatling for your load generation and reporting purposes.
- When a graph shows sudden spike, it is an indication of a ‘possible’ coordinated omission. If a graph is smoothly growing, it is an indication that there is no bad data.
- There is no point in looking at percentile graphs if you don’t have performance goals set for your service. If you are comparing two systems and your target is 20ms, then you could plot graphs and see what is the maximum throughput each system supports while maintaining latency at 20 ms.
Coordinated omission
Classic measurement piftall in latency benchmarking. It happens whenever your measurement code “pauses” issuing new requests while the system under test is slow, so you never observe the full extent of the delay
Linux Kernel’s Read-Copy-Update (RCU) pattern
Optimised for read-mostly situations
A typical RCU update sequence
- Remove pointers to a data structure, so that subsequent readers cannot gain a reference to it.
- Wait for all previous readers to complete their RCU read-side critical sections.
- Reclaim data structure: All-or-nothing execution, i.e. No half-written state. Only 4-bit or 8-bit aligned values can be atomic. The problem is, most objects exceed this value, so how can we still do transactional operations on this? Use a pointer to a lookup table, which itself are pointers to the actual objects
Seqlock
- A special locking mechanism used in Linux for supporting fast writes of shared variables between 2 parallel OS routines.
- A reader-writer consistent mechanism which avoids the problem of writer starvation.
- A sequence number in addition to a lock.
- Lock supports sync between 2 writers and counter indicates consistency in readers.
- DOES NOT WORK WITH POINTERS, because any writer could invalidate a pointer that a reader has already followed.
Read
pub fn read(&self, result: &mut T) {
loop {
let v1 = self.version.load(Ordering::Acquire);
compiler_fence(Ordering::AcqRel); // don't let data read be before v1 read
*result = unsafe { *self.data.get() };
compiler_fence(Ordering::AcqRel); // don't let v2 read be before data read
let v2 = self.version.load(Ordering::Acquire);
if v1 == v2 && v1 & 1 == 0 {
return;
}
}
}Write
pub fn write(&self, val: &T) {
let v = self.version.fetch_add(1, Ordering::Release);
compiler_fence(Ordering::AcqRel); // similar logic
unsafe { *self.data.get() = *val };
compiler_fence(Ordering::AcqRel); // similar logic
self.version.store(v.wrapping_add(2), Ordering::Release);
}Real-time Linux
A standard Linux kernel that’s been built with the PREEMPT_RT patch so that
- Interrupt handlers run in threads (why is this good?): Prioritisation & CPU-affinity, Preemptibility & bounded latencies
- Most locks become preemptible mutexes
- Worst-case scheduling latencies stay bounded
vSyscall vs vDSO
https://stackoverflow.com/questions/19938324/what-are-vdso-and-vsyscall
Standard RAID levels
The main purpose of most RAID (redundant array of independent disks) levels is to reduce the risk of data loss by providing redundancy. It comprises a basic set of RAID configurations that employ the techniques of striping, mirroring or parity to create large reliable data stores from multiple general-purpose computer HDDs.
RAID 0 (Stripe set/volume)
It splits (stripes) data evenly across two or more disks, without any redundancy with a focus on speed.
RAID 1 (Mirror)
It consists of an exact copy of a set of data on two or more disks.
RAID 5 (Parity check)
It consists of block-level striping with distributed parity. Parity information is distributed among the drives. It requires that all drives but one be present to operate. Upon failure of a single drive, subsequent reads can be calculated from the distributed parity such that no data is lost. It can tolerate the failure of one disk.
Kernel Bypass
https://jackiedinh8.medium.com/learning-kernel-bypass-networking-in-a-simpler-way-7d3aa4547314
- Handles ethernet frames in Userspace rather than Kernel Space
- Direct interaction with network devices instead of using Linux system calls to send/receive data through Linux Kernel
Read PCI configuration space
Enable DMA
Get BAR of device, where the device’s MMIO region is located
Steps to initialize a device:
- Reset device by setting reset bit of control register
- Initialize transmit queue by setting all buffers empty
- Initialize receive queue by allocating memory for receive buffers. Note that device only access to physical memory address
- Setup transmit and receive control bits
- Enable receive interrupts
Network packet flow
── Receive Path ────────────────────────────────────────────────
Lowest layer
[ NIC hardware ]
↓ DMA
[ NIC RX ring ] ← hardware RX descriptors
↓ NAPI polls/IRQs
[ sk_buff allocation ] ← packet wrapped in sk_buff
↓ ingress qdisc* ← only if you’ve run `tc qdisc add … ingress`
[ socket receive queue ] ← queue of sk_buffs, capped by SO_RCVBUF
↓ recv()/read()
Your application
Highest layer
── Transmit Path ───────────────────────────────────────────────
Highest layer
Your application
↓ send()/write()
[ socket send buffer ] ← TCP/UDP layer queue, capped by SO_SNDBUF
↓ packetization
[ sk_buff enqueue ] ← each packet again becomes an sk_buff
↓ egress qdisc ← fq_codel, pfifo_fast, HTB→fq_codel, etc.
[ NIC TX ring ] ← hardware TX descriptors
↓ DMA
[ NIC hardware ]
Lowest layersk_buff (socket buffer)
In Linux networking, every socket (TCP, UDP, raw, etc.) is backed by two kernel-side buffers
- Send buffer (
sk_sndbuf) - Receive buffer (
sk_rcvbuf)
qdisc (queueing discipline)
Kernel’s way of holding, ordering and scheduling packets as they go in/out of a network interface
Classless vs Classful
Classless qdiscs
exactly 1 bucket, no hierarchy
pfifo_fast (default on many kernels): three bands, simple priority.
- Incoming packets are classified into 1 of 3 bands.
- Within each band, FIFO.
fq_codel (modern default on many distros): fair-queue + CoDel AQM for low latency [USE THIS].
- Flow hashing.
- Round robin dequeue.
- CoDel drops: within each flow-queue, if packets experience too much sojourn time (i.e. Sitting in queue > target delay), it starts dropping to drain the queue and keep latency low.
qdisc fq_codel 0: parent :4 limit 10240p flows 1024 quantum 1514 target 5ms interval 100ms memory_limit 32Mb ecn drop_batch 64
Classful qdiscs
Allow you to carve that root queue into named “classes” (hierachies), each with its own child qdisc
HTB (Hierarchical Token Bucket)
It is shaped by guaranteed and maximum rates per class.
ratebucket: tokens added at the guaranteed rate (e.g. 20 Mb/s)ceilbucket: tokens added at the maximum allowed rate (e.g. 100 Mb/s)- If the
ratebucket is empty, the class can still send up to itsceilrate - but only if there are unused tokens in its parent's bucket
NAPI (New API)
It’s an interface to use interrupt mitigation techniques for networking devices in the Linux Kernel. Such an approach is intended to reduce the overhead of packet receiving. The idea is to defer incoming messages handling until there is a sufficient amount of them so that it’s worth handling them all at once.
It should be built into almost every modern NIC driver.
Chronicle Tuning
- Disable Hyperthreading
- Core Isolation
- P-State Power: Frequency and voltage at which the processor runs so as to reduce the power consumption of the CPU
- C-State Power: Generally, higher C-states turn off more parts of the CPU, which significantly reduce power consumption
- IRQ Rebalance Scheduling: Linux automatically distributes interrupt requests (IRQs) across CPU cores to balance load
JSON Parsing
Tree-based Parsing (DOM Parsing)
- Rust’s
serdeprovides a similar API to Java'sJackson, which parses the JSON into a value tree - Simple to use, recommended for less performance-sensitive apps
Event-based/driven JSON parser
- Processes JSON input by generating events (callbacks) as it encounters parts of the JSON document, which can lead to improved performance and reduced memory usage, especially for large documents
- Some implementations support streaming and incremental parsing
Why might it be faster than some Tree-Based Parsing?
- Skip generating intermediate representations
- Zero allocation, because the parser does not build a full object hierarchy in memory
- Obviously, our own logic should be zero allocation as well
Allocations between Garbage-Collected and Native languages
Garbage-Collected
- Often use a bump-pointer strategy for allocating new objects in the young generation
- Can be as simple as advancing a pointer in a contiguous memory region
- Stop-the-world pause resulting from garbage collection can affect tail-latency, though objects in young gen usually do not affect latency much, because modern GCs are very optimised
Native
- Allocation typically goes through a general-purpose allocator
- Slightly more overhead because they need to handle a wider variety of allocation sizes and fragmentation
- Switch to using bump allocators in performance-critical sections? Or better, do zero allocation in hot-path
- More predictable latency using a general purpose memory allocator
- In rust, deallocation using
Drop
Conclusions
For rust-infra, zero allocation in hot-path is the way to go -> reuse data structures as much as possible -> initialise data structures at startup
What kind of clock to use?
Precision considerations
std::Time::Instant: Choose precise clock based on OSstd::Time::SystemTimelibc::gettimeofday: Requires rather heavy computationlibc::clock_gettime(libc::CLOCK_REALTIME): Non-monotonic but wall-clock timelibc::clock_gettime(libc::CLOCK_MONOTONIC): Represents time since an unspecified point. Can still be affected albeit incrementally as it will still try to synchronise with NTP, hence slowing down/speeding up to keep up with NTP, but still adhering to monotonicitylibc::clock_gettime(libc::CLOCK_BOOTTIME)(linux only): Similar to 5, but includes time spent suspendedlibc::clock_gettime(libc::CLOCK_UPTIME_RAW)/libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW)(linux only): Often referred to as a “raw” monotonic clock, this clock is not subject to any frequency adjustments (like those made by NTP or adjtime) and represents the raw hardware counter. Most precise usually, and recommended if we are doing same-box performance benchmarkings
Escape Analysis
Analyse where the pointer can be referenced from, i.e. local function, class, global, etc.
Get Tzehenn’s stories in your inbox
Join Medium for free to get updates from this writer.
One of the optimisations performed by JVM/JIT -> reduce heap allocations. If pointer can only be locally referenced, don’t even need to allocate on heap, just create on stack.
What I noticed
In order to reduce GC and auto-boxing, some implementations of libraries use primitive arrays as their underlying data structure int[] arr. Array is quite a performant data structure due to its cache-friendliness and fast constant lookup.
Branchless Programming
Conditional Assignments vs Bitwise Operations
max(a, b) -> a - ((a - b) & ((a - b) >> (sizeof(int) * CHAR_BIT - 1)));
Conditional Move Instructions
These instructions allow data to be moved conditionally without creating a branch.
Address Offsets/Lookup Tables
Data denormalisation?
Aiding Branch Prediction
Don’t inline code that is not going to be called often, to avoid instruction cache thrashing.
Softirq (Interrupt Masking)
A softirq is a software interrupt request in the Linux Kernel. It’s a way for the kernel to defer work that needs to be done, but that can be delayed without causing any problems. They are used for tasks such as network packet processing, disk I/O, and timer management.
Softirqs are implemented using a special type of kernel thread called a softirqd. The thread runs at a lower priority than the main kernel thread.
Why do we need to know this?
Even when CPUs are isolated from the OS, it’s still possible for application threads to be interrupted, introducing unwanted jitter.
This is usually down to kernel threads: processes that perform work on behalf of the OS. Kernel threads have a higher priority than user application threads, so they will always interrupt the application when scheduled.
The OS will schedule a kernel thread onto a CPU for a number of reasons. One of the most common is for servicing interrupts.
When a hardware device (e.g. network card) wishes to notify the OS of a change in state (e.g. a data packet has arrived), it sends an interrupt signal to a specific CPU. The OS will halt any currently running process, and invoke an interrupt handler which will then add an item to a queue to be processed by a softirq thread. This process will halt any application threads that are supposed to execute on the interrupted CPU.
CPU Speed
Modern CPUs are designed to be power efficient, which means the OS will typically try to scale down the clock rate when there is no activity.
On current kernels, this is handled by the CPU scaling governor
Dealing with Kernel Threads
Quite a few kernel threads like kworker, best is to reduce their frequency of being run
Hardware interrupts
Steer these interrupts away from protected resources
Level-triggered event (default) vs Edge-triggered event
In level-triggered mode, the event notification mechanism notifies the application as long as the condition (such as “data is available to read” or “buffer space is available to write”) remains true.
- Arguably more intuitively for the user?
can_write: space on the kernel to write intocan_read: something to read from the kernel
Edge-triggered mode signals events only when there is a change in the state of the file descriptor, which means you must process it completely
- Must put the file descriptors into non-blocking mode, so for read/write you can safely loop‑drain until
EAGAIN(until more data appears)/EPOLLOUT(until more space appears) and then return toepoll_wait
Server related helpers
Testing UDP connectivity between 2 servers
Sender: echo "Test" | nc (-s <src_ip>) -vu <recv_ip> <recv_port>
Receiver: nc -vul (<recv_ip) <recv_port>
Testing Stunnel Connectivity
telnet <ip> <port>
etc/stunnel/stunnel.conf
Testing General HTTP Connectivity
curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: stream.binance.com" -H "Origin: https://stream.binance.com" http://stream.binance.com:443
SNI (Server Name Indication)
SNI is an extension to the SSL/TLS protocol that allows a client to indicate the hostname it’s trying to connect to during the initial handshake
Firewall might bind the domain to a specific IP instead of domain
rsync -zar -e "ssh -i ~/.ssh/id_ed25519" --exclude='target/' ./ user@ip:~/xxx
TCP Format
- Source Port(16 bits): It holds the source/transmitting application’s port number and helps in determining the application where the data delivery is planned.
- Destination Port (16 bits): This field has the port number of the transmitting application and helps to send the data to the appropriate application.
- Sequence Number (32 bits): It ensures that the data is received in proper order by ordered segmenting and reassembling them at the receiving end.
- Acknowledgment Number (32 bits): This field contains the upcoming sequence number and it acknowledges the feedback up to that.
- Data Offset (4 bits): The data offset field indicates the starting point of the TCP data payload also storing the size of the TCP header.
- Control Flags (9 bits): TCP uses a few control flags to regulate communication. Some of the important flags include:
- SYN (Synchronize): Responsible for connecting the sender and receiver.
- ACK (Acknowledgment): Its purpose is transfer the acknowledgement of whether the sender has received data.
- FIN (Finish): It informs whether the TCP connection is terminated or not.
- RST (Reset): Mainly used to reset the connection when an error occurs.
- Window Size (16 bits): The size of the sender’s receive window is specified by this property.
- Checksum (16 bits): It reveals if the header was damaged during transportation. This is calculated including a “Pseudoheader”.
- Urgent Pointer (16 bits): This field points to the packet’s first byte of urgent data.
- Options (Variable length): This field represents the different TCP options.
- Data Payload: This field mainly contains the information which is the actual application data that is being transmitted.
UDP Format
- Source Port: Source Port is a 2 Byte long field used to identify the port number of the source.
- Destination Port: It is a 2 Byte long field, used to identify the port of the destined packet.
- Length: Length is the length of UDP including the header and the data. It is a 16-bit field.
- Checksum: Checksum is 2 bytes long field. It is the 16-bit one’s complement of the one’s complement sum of the UDP header, the pseudo-header of information from the IP header, and the data, padded with zero octets at the end (if necessary) to make a multiple of two octets.
ICMP Format
Type (8-bit): The initial 8-bit of the packet is for message type. It provides a brief description of the message so that the receiving network would know what kind of message it is receiving and how to respond to it. Some common message types are as follows:
- Type 0 — Echo reply
- Type 3 — Destination unreachable
- Type 5 — Redirect Message
- Type 8 — Echo Request
- Type 11 — Time Exceeded
- Type 12 — Parameter problem
Code (8-bit): Code is the next 8 bits of the ICMP packet format. This field carries some additional information about error messages and types.
Checksum (16-bit): Last 16 bits are for the checksum field in the ICMP packet header. The checksum is used to check the number of bits of the complete message and enable the ICMP tool to ensure that complete data is delivered.
The next 32 bits of the ICMP Header are Extended Header, which has the work of pointing out the problem in IP Message. Byte locations are identified by the pointer which causes the problem message and the receiving device looks here for pointing to the problem.
The last part of the ICMP packet is Data or Payload of variable length. The bytes included in IPv4 are 576 bytes and in IPv6, 1280 bytes.
RFC 792 for ICMP:
When a router or host sends back an ICMP error, it must include in the ICMP payload
- The IP header of the original packet that triggered the error
- At least the first 8 bytes of that original packet’s payload (which is usually the transport header, e.g. TCP/UDP)
IPv4 Format
- Version (4 bits): This field contains a value of four bits which is 0100 generally. This value is utilized in distinguishing between IPv4 and IPv6, using four bits.
- Header Length (4 bits): This value is 4 bits in size and it represents how many 32-bit words are present in the IP header. In short, it is also called HE-LEN.
- Type of Service (TOS) (8 bits): This field mainly deals with information about how the quality of the service is being delivered. The first 3 bits provides distinction and prioritization of IP packets depending on certain service needs, such as precedence, delay, throughput, dependability, and cost.
- Total Length (16 bits): The total length of the IP packet is stored in bytes. This value and the HE-LEN sums up to the value of the Payload. Also includes TCP header
- Identification (16 bits): This field gives a specific IP packet a distinctive identity. This helps to identify the fragments of the an IP Datagram Uniquely.
- Flags (3 bits): Contains control flags for packet fragmentation and reassembly, such as the “Don’t Fragment” and “More Fragments” flags.
- Fragment Offset (13 bits): After a packet is fragmented and put back together, this field contains the location of it inside the original packet. It represents the number of Data Bytes ahead of the particular fragment in the specific Datagram.
- Time to Live (TTL) (8 bits): This field specifies the total lifetime of the Data packet in the internet system. This field indicates how many hops (routers) an IP packet can make before being terminated. This value goes from 0–255.
- Protocol (8 bits): This IPv4 header specifies the type of transport layer protocol, such as TCP, UDP, or ICMP, to which the IP packet will be routed. For example, TCP is indicated by number 6 and UDP protocol is denoted by number 17.
- Header Checksum (16 bits): This is an error checking layer which is added to identity errors in the header. By comparing the IP header with its checksum for error detection, it ensures the IP header’s integrity.
- Source IP Address (32 bits): The IPv4 sender’s 32-bit address is represented by this value.
- Destination IP Address (32 bits): This value represents the 32-bit IP address of the intended recipient.
- Options (variable length): This field has options and parameters for security, record route, time stamp, etc. You can see that the End of Options, or EOL, usually marks the end of the list of options components.
IPv6 Format
ARP Format
Hardware type: This is 16 bits field defining the type of the network on which ARP is running. Ethernet is given type 1.
Protocol type: This is 16 bits field defining the protocol. The value of this field for the IPv4 protocol is 0800H.
Hardware length: This is an 8 bits field defining the length of the physical address in bytes. Ethernet is the value 6.
Protocol length: This is an 8 bits field defining the length of the logical address in bytes. For the IPv4 protocol, the value is 4.
Operation (request or reply): This is a 16 bits field defining the type of packet. Packet types are ARP request (1), and ARP reply (2).
Sender hardware address: This is a variable length field defining the physical address of the sender. For example, for Ethernet, this field is 6 bytes long.
Sender protocol address: This is also a variable length field defining the logical address of the sender For the IP protocol, this field is 4 bytes long.
Target hardware address: This is a variable length field defining the physical address of the target. For Ethernet, this field is 6 bytes long. For the ARP request messages, this field is all Os because the sender does not know the physical address of the target.
Target protocol address: This is also a variable length field defining the logical address of the target. For the IPv4 protocol, this field is 4 bytes long.
RTP Format
- Version (2 bit) — It defines version number. The current version is 2.
- P (1 bit) — If value is 1, then it denotes presence of padding at end of packet and if value is 0, then there is no padding.
- X (1 bit) — If value of this field is set to 1, then it indicates an extra extension header between data and basic header and if value is 0 , then there is no extra extension.
- Contributor count (4 bits) — It indicates the number of contributors. Here, the maximum possible number of contributors is 15 as a 4-bit field can allow numbers from 0 to 15.
- M (1 bit) — It is used as an end marker by application to indicate the end of its data.
- Payload types (7 bits) — It indicates the type of payload. We list applications of some common types of payload.
- Sequence Number (16-bits) — It is used to give serial numbers to RTP packets. It helps in sequencing. The sequence number for first packet is given a random number and then every next packet’s sequence number is incremented by 1. This field mainly helps in checking lost packets and order mismatch.
- Time Stamp (32 bits) — It is used to find relationships between times of different RTP packets. The timestamp for the first packet is given randomly and then a time stamp for the next packets given by sum of previous timestamp and time taken to produce the first byte of the current packet. The value of 1 clock tick varies from application to application.
- Synchronization Source Identifier (32 bits) — It is used to identify and define the source. The value for this source identifier is a random number that is chosen by source itself. This mainly helps in solving conflict arises when two sources start with the same sequencing number.
- Contributor Identifier (32 bits) — It is used for source identification where there is more than one source present in session. The mixer source uses Synchronization source identifier and other remaining sources (maximum 15) use Contributor identifier.
Ethernet Format
- PREAMBLE: Ethernet frame starts with a 7-Bytes Preamble. This is a pattern of alternative 0’s and 1’s which indicates starting of the frame and allow sender and receiver to establish bit synchronization. Initially, PRE (Preamble) was introduced to allow for the loss of a few bits due to signal delays. But today’s high-speed Ethernet doesn’t need a Preamble to protect the frame bits. PRE (Preamble) indicates the receiver that frame is coming and allow the receiver to lock onto the data stream before the actual frame begins.
- Start of frame delimiter (SFD): This is a 1-Byte field that is always set to 10101011. SFD indicates that upcoming bits are starting the frame, which is the destination address. Sometimes SFD is considered part of PRE, this is the reason Preamble is described as 8 Bytes in many places. The SFD warns station or stations that this is the last chance for synchronization.
- Destination Address: This is a 6-Byte field that contains the MAC address of the machine for which data is destined.
- Source Address: This is a 6-Byte field that contains the MAC address of the source machine. As Source Address is always an individual address (Unicast), the least significant bit of the first byte is always 0.
- Length: Length is a 2-Byte field, which indicates the length of the entire Ethernet frame. This 16-bit field can hold a length value between 0 to 65535, but length cannot be larger than 1500 Bytes because of some own limitations of Ethernet.
- Data: This is the place where actual data is inserted, also known as Payload . Both IP header and data will be inserted here if Internet Protocol is used over Ethernet. The maximum data present may be as long as 1500 Bytes. In case data length is less than minimum length i.e. 46 bytes, then padding 0’s is added to meet the minimum possible length.
- Cyclic Redundancy Check (CRC): CRC is 4 Byte field. This field contains a 32-bits hash code of data, which is generated over the Destination Address, Source Address, Length, and Data field. If the checksum computed by destination is not the same as sent checksum value, data received is corrupted.
- VLAN Tagging: The Ethernet frame can also include a VLAN (Virtual Local Area Network) tag, which is a 4-byte field inserted after the source address and before the EtherType field. This tag allows network administrators to logically separate a physical network into multiple virtual networks, each with its own VLAN ID.
- Jumbo Frames: In addition to the standard Ethernet frame size of 1518 bytes, some network devices support Jumbo Frames, which are frames with a payload larger than 1500 bytes. Jumbo Frames can increase network throughput by reducing the overhead associated with transmitting a large number of small frames.
- Ether Type Field: The EtherType field in the Ethernet frame header identifies the protocol carried in the payload of the frame. For example, a value of 0x0800 indicates that the payload is an IP packet, while a value of 0x0806 indicates that the payload is an ARP (Address Resolution Protocol) packet.
- Multicast and Broadcast Frames: In addition to Unicast frames (which are sent to a specific destination MAC address), Ethernet also supports Multicast and Broadcast frames. Multicast frames are sent to a specific group of devices that have joined a multicast group, while Broadcast frames are sent to all devices on the network.
- Collision Detection: In half-duplex Ethernet networks, collisions can occur when two devices attempt to transmit data at the same time. To detect collisions, Ethernet uses a Carrier Sense Multiple Access with Collision Detection (CSMA/CD) protocol, which listens for activity on the network before transmitting data and backs off if a collision is detected.
Trading terminologies
Market Exposure
Dollar amount of funds or % of broader portfolio that is invested. Usually expressed as a % of total holdings, e.g. 10% of a portfolio being exposed to the oil/gas sector OR a $50k in Tesla stock.
It’s a tool used to measure and balance risk in an investment portfolio. Focuses on overall sensitivity to the movements in the market.
Support/Resistance level
Imaginary lines that “prevent” the price of stock from moving past them.
Products
Future
Linear (USDS-M / USDT-M)
Linear futures are futures contracts where the price of the contract moves in direct proportion to the price of the underlying asset. Linear futures are typically settled in the same asset. If you are trading a linear futures contract on Bitcoin (BTC), for example, you would be paying or receiving the equivalent value of Bitcoin upon settlement.
Inverse (Coin-M)
Inverse futures are futures contracts where the price of the contract moves inversely to the price of the underlying asset. Inverse futures are typically settled in a stable coin, like USDT (Tether) or USD, rather than the underlying asset.
Swap (Perpetual Futures or Perps)
A financial contract in which one party exchanges/swaps the values/cash flows of one asset for another. Of the two cash flows, one value is fixed and one is variable and based on an index price/interest rate/currency exchange rate.
E.g. A pays B an amount equal to 6% per annum on a notional principal (doesn’t change throughout the contract) of $20 million. B pays A an amount equal to one-year LIBOR + 1% per annum on a notional principal of $20 million.
Spot Trading
The purchase/sale of a foreign currency/financial instrument/commodity for instant delivery on a specified spot date.
Spot index: A financial metric that represents the current market price of a particular asset/commodity/ financial instrument at a specific point in time. It’s used to reflect the real-time value of an asset in the spot market.
Delta
A risk metric that estimates the change in the price of a derivative, such as an options contract, given a $1 change in its underlying security. It’s represented by the symbol Δ dv/dt. Mathematically, it is the first-order derivative of the derivative’s value with respect to the underlier’s price.
A product that uses this concept somewhat is the Delta One product. A Delta One product gives the investor the same exposure as if the investor were to own the underlying asset. E.g., an investor would like to “own” the S&P500. The first alternative for the investor would be to buy all the 500 different shares that make up the S&P500, in the same proportions as the S&P500. If done correctly, the returns to the investor will now be the same as the return of the index. The investor has a Delta One position to the index — in this case, by exactly replicating the index.
Index Price
Weighted average spot price across multiple exchanges
Mark Price
A reference price that is calculated from the underlying index of a derivative and is often calculated as a weighted average of the spot price of an asset across multiple exchanges. The aim of this calculation is to avoid price manipulation on a single exchange and provide a more accurate representation of the asset’s value.
Mark price = spot index price + EMA (Exponential Moving Average) of basis price
To illustrate, for a particular pair of symbols, there can be only 1 index price (because it’s unique to the pair duh), but multiple mark prices corresponding to each type of derivative
Basis price
Difference between the spot price of that commodity and its future prices at a given point in time.
Maximum Extractable Value (MEV)
MEV (Maximum Extractable Value) arbitrage refers to the practice of capturing “free” profit opportunities that arise within a single block on a blockchain by reordering, including, or excluding transactions. It’s most commonly discussed on Ethereum but applies to any smart‐contract platform with an order‐flow.
Defi Front-Running
- Bot spots Alice’s 10 ETH→DAI pending, computes the slippage impact, and crafts a buy of the same token with a slightly larger gas price.
- Miner (or MEV relay) orders the bot’s tx before Alice’s, so the pool’s price moves up.
- Alice’s swap now gets executed at that new, worse rate, “sandwiched” between the bot’s two trades.
- Bot immediately sells at the inflated price, capturing the spread.
Defi Back-Running
- Monitoring Mempool: Back-runner continuously monitors the Ethereum Mempool, looking for potentially profitable transactions.
- Identify profitable transactions: When back-runners identify a transaction that could have a significant impact on the price of a token or asset, they analyze its expected results. For example, identifying a buy order for 1,000 ETH on the chain could cause the price of ETH in Uniswap to rise by 10%.
- Constructing a new transaction: Back-runner constructs a new transaction that takes advantage of the expected results of the original transaction after it is executed. For example, by quickly buying ETH at a low price in SushiSwap and cross-chaining it back to the ETH mainnet, and finally constructing a sell order for ETH.
- Priority Gas Auction: Back-runners bid high gas fees to increase the chances of their transactions being included in the next block after the original transaction.
- If successful, the back-runner’s trade is executed immediately after the original trade, enabling them to profit from the price movement caused by the original trade.






