">
 

6 characters, 32 symbols, 3 rooms a minute: the arithmetic behind account-less room codes

Iniciado por joomlamz, Hoje at 03:25

Respostas: 1   |   Visualizações: 1

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Saudações à comunidade do **webmastersmz.com**. Como especialista em tecnologia, analisei o artigo técnico sobre a mecânica de geração de códigos de salas temporárias (do tipo *account-less*) e apresento aqui os pontos fundamentais desta abordagem.

### Análise Técnica: A Aritmética por trás dos Códigos de Sala

O artigo aborda um desafio clássico de engenharia de sistemas: como garantir a unicidade de identificadores (IDs) em um ambiente de alta concorrência sem depender de uma base de dados centralizada ou de contas de utilizador.

**Os pontos cruciais levantados são:**

1.  **Espaço de Endereçamento (Entropia):** Com 6 caracteres e um conjunto de 32 símbolos possíveis, temos um total de $32^6$ combinações, o que resulta em aproximadamente **1,07 mil milhões de códigos únicos**. Este é um número vasto, mas finito.
2.  **A Armadilha do Paradoxo do Aniversário:** O artigo alerta corretamente para o facto de que, à medida que geramos mais códigos, a probabilidade de colisão aumenta drasticamente muito antes de esgotarmos o conjunto total. Num sistema que cria 3 salas por minuto, a gestão do ciclo de vida destas salas (TTL - *Time to Live*) é crítica para evitar colisões.
3.  **Eficiência de Memória:** O uso de códigos curtos (6 caracteres) é excelente para a experiência do utilizador (UX), permitindo uma digitação rápida e menos erros, mas exige que o sistema de *backend* implemente uma estratégia robusta de limpeza (expiração) para manter a integridade do conjunto de códigos disponíveis.

**Incentivo ao debate:**
Como gerem este tipo de tokens nos vossos projetos? Estão a utilizar algoritmos de *hashing* com truncagem, ou preferem gerar IDs aleatórios com validação de unicidade em cache (como o Redis)? Gostaria de ler as vossas experiências sobre como escalam este tipo de sistemas para evitar "colisões" em horários de pico. Deixem as vossas opiniões e implementações aqui no fórum!

---

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com.

6 characters, 32 symbols, 3 rooms a minute: the arithmetic behind account-less room codes



Tópico: 6 characters, 32 symbols, 3 rooms a minute: the arithmetic behind account-less room codes
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
A visitor clicks Create, picks two to four players, and gets a code like K7QM2P. No account, no email, nothing that survives the tab closing. That code is the only handle the room has, so it has to carry three jobs at once: a human can retype it, a script cannot guess a live one too cheaply, and the server can throw it away without asking anyone.

Four numbers decide how well it does those jobs. I wrote them down while building SameWord, mostly so I would stop changing them.



32 symbols, and the four characters I removed


The alphabet is ABCDEFGHJKLMNPQRSTUVWXYZ23456789: the 26 letters minus I and O, plus the digits 2 through 9.

I dropped I, O, 0 and 1 because they are the four characters people misread when a code is spoken out loud, written on paper, or set in a font where the counters are tight. A room code that gets retyped wrong is worse than a room code that is one character longer, because the failure is silent. The person does not get an error about their eyesight, they get "room not found" and assume the game is broken.

The cost is measurable. A 36-symbol alphabet over 6 positions gives 2,176,782,336 codes. Thirty-two symbols gives 1,073,741,824. I traded away 1.1 billion possible codes for four characters that never get confused. Overnight that looked like a bad deal; it stopped looking like one the first time I read a code to someone over a call.



What a billion codes actually buys


The useful question is not how many codes exist but how often two live rooms would collide, which is the birthday problem. With M = 32^6, the probability that any two of n rooms share a code is about 1 - exp(-n(n-1) / 2M).

Live rooms
Chance of at least one collision

100
0.00046% (about 1 in 217,000)

1,000
0.047% (about 1 in 2,150)

10,000
4.5%

100,000
99.0%

That last row is the one worth keeping. Six characters is plenty for a few thousand rooms and hopeless at a hundred thousand. The number does not decay gracefully, it falls off a cliff, so the day the site grows past that line the answer is a seventh character or a prefix, not "watch it more closely".

I did not add collision checking on create. The check would be one storage read, but at the scale where collisions actually happen the read is the least of the problems, and at the scale where they do not, it is a tax on every room for a 1-in-217,000 event.



Three rooms a minute, counted in memory


Creating a room is a POST with no auth, so it needs some ceiling. The rule is three per IP per minute, on a 60-second rolling window:

export const CREATE_RATE_LIMIT = 3;
export const CREATE_RATE_WINDOW_MS = 60_000;

Three is not a security number. It is the point where a person sharing an office or a home connection, plus a friend on the same wifi, does not get locked out while a loop that opens rooms still stops after the fourth. The hits live in a Map keyed by IP, and when the map passes 2,000 keys the expired entries get swept, so a burst of unique IPs cannot grow it without bound.

The honest limitation: that map is per isolate. Cloudflare runs many isolates, each with its own copy, so the effective ceiling is three times the number of isolates that happen to be warm, not three. As a defence against someone determined to fill the storage it is close to useless. As a defence against a script or an impatient double-click it works, which is the failure I actually see.



A wrong code returns 404. It never creates a room


This is the rule I would keep if I could keep only one. Look up a code that does not exist and you get room_not_found, a 404, and nothing else happens. Nothing is created, nothing is reserved, no empty room is written to storage.

The alternative is tempting: a code that does not exist is a room waiting to be made, so create it and let the visitor in. That is how a single mistyped character turns into a live empty room holding a code for six hours, and how a crawler that walks /room/AAAAAA through /room/ZZZZZZ fills your storage with rooms nobody asked for.

Codes are case-insensitive on the way in, because nobody types uppercase reliably on a phone. The server uppercases the six characters before the lookup. But the four characters I removed from the alphabet are not silently mapped to their lookalikes: type an O where an 0 would be and the validation fails, so the request lands on the same 404. Guessing what someone meant is how you end up with two rooms that look identical on a printed card.



Six hours, checked when someone reads


A room dies after six hours without a visit. There is no alarm, no scheduled job, no queue of expiring rooms:

export const ROOM_TTL_MS = 6 * 60 * 60 * 1000;

The check happens on read. Every request that touches a room compares the last activity against that window, and an expired room is treated as gone. The trade is straightforward. Nobody reading means nothing is freed, so stale rooms sit in storage until someone knocks or the platform cleans up behind me. In exchange, creating a room schedules nothing, and there is no second way for a room to change state that I have to reason about when a request comes in.

The same shape shows up in the smaller timers. A player counts as online for 20 seconds after their last heartbeat; the heartbeat itself is written to storage at most once every 5 seconds, because persisting every poll would be a write per player per second for a value that only needs to be roughly fresh. Two numbers, one purpose: keep the state derivable from the last write instead of from a running clock.



What this is not


None of this is a general pattern for identifiers. It is a set of choices for one specific object: a thing that lives for six hours, is typed by hand, and is allowed to die quietly. If your handle is permanent, or appears on an invoice, or has to survive a domain move, the arithmetic above is the wrong arithmetic and you should be using something long and opaque.

But if the object is a room with a six-hour life and no account behind it, the code is the product surface. It is the thing people read to each other, the thing that fills storage when it is mistyped, and the thing that decides how many rooms you can hand out before the birthday problem makes them collide. Four numbers, and I would rather have them in a table than in my head.

The game is at playsameword.com if you want to see the codes in the wild.


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: