r/madeinpython • u/TastyCollege9639 • 11d ago
Built pynltp: an asyncio UDP library that recovers up to 35% dropped packets without waiting on retransmit
Wanted to share a Python networking package I have been building and testing called pynltp (available via pip install pynltp, MIT licensed).
Why I wrote it:
I needed to pull 50 KB to 250 KB JSON sensor batches and send urgent control commands over lossy Wi-Fi and 4G links where 15% to 30% of packets randomly drop. Over normal TCP sockets, Python apps stall for 15+ seconds because the OS kernel assumes packet loss means router congestion and backs off the send window. Raw asyncio DatagramProtocol sockets avoid the stall, but you lose ordering, encryption, and any multi-packet payload if a single datagram disappears.
How pynltp works under the hood in Python:
- Before encrypting or slicing a payload, it runs a compact pure-Python LZ4 block pass on repetitive JSON/CSV data, which usually shrinks telemetry batches ~6x so far fewer UDP packets hit the socket.
- Each session performs an ephemeral X25519 key exchange (with optional pre-shared key), derives directional keys via HKDF-SHA256, and authenticates every UDP frame with ChaCha20-Poly1305 plus a 512-packet bitmask to drop replayed or spoofed packets in O(1).
- Instead of stopping on every lost packet to wait for an ACK/NACK round-trip, each block is split into k systematic data shards plus m parity shards over GF(28) using precomputed 256-byte log/exp tables and Cauchy matrix inversion. As soon as any k shards arrive at the asyncio transport, the original buffer is reconstructed and SHA-256 verified immediately.
- Urgent 1-packet reflex messages ride a separate packet type outside the bulk reassembly dictionary so alerts never get stuck behind a large file transfer.
Benchmarks and tradeoffs:
Using Linux tc netem set to 20% random packet loss and 80 ms RTT (10 runs each), transferring 100 KB of structured JSON took 2.65s +/- 0.31s with pynltp compared to 18.35s +/- 4.12s over kernel TCP BBR. On clean wired networks (<1% loss), standard TCP or asyncio streams are faster because the Cauchy parity shards add ~25-35% bandwidth overhead that is wasted when nothing drops.
It also speaks the exact same 16-byte binary header as a companion C99 Arduino library and JS client, so a Python asyncio server on a Raspberry Pi can talk directly to ESP32/ESP8266 nodes.
Source code, wire format docs, and netem benchmark scripts:
https://github.com/indian-aman/necklink/tree/main/packages/nltp
PyPI package:
https://pypi.org/project/pynltp/
Would appreciate any code review or ideas on speeding up the pure-Python GF(28) row-reduction loop!

