惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
S
Securelist
小众软件
小众软件
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 司徒正美
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
O
OpenAI News
Cloudbric
Cloudbric
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
TaoSecurity Blog
TaoSecurity Blog
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
V2EX
PCI Perspectives
PCI Perspectives
T
Troy Hunt's Blog
Schneier on Security
Schneier on Security
P
Palo Alto Networks Blog
M
MIT News - Artificial intelligence
V2EX - 技术
V2EX - 技术
阮一峰的网络日志
阮一峰的网络日志
Hacker News - Newest:
Hacker News - Newest: "LLM"
G
Google Developers Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Last Watchdog
The Last Watchdog
The Register - Security
The Register - Security
腾讯CDC
N
News and Events Feed by Topic
C
Check Point Blog
爱范儿
爱范儿
T
Tailwind CSS Blog
Webroot Blog
Webroot Blog
P
Proofpoint News Feed
S
Schneier on Security
MyScale Blog
MyScale Blog
N
News | PayPal Newsroom
Recorded Future
Recorded Future
T
Tenable Blog
I
InfoQ
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Microsoft Security Blog
Microsoft Security Blog
Simon Willison's Weblog
Simon Willison's Weblog
Engineering at Meta
Engineering at Meta

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Protocol Buffers in Elixir
Mathieu Kerjouan · 2026-06-26 · via DEV Community

Serializing data is an important topic. The main goal is to convert some kind of data in another format compatible for some tasks, usually, to send them over the network. JSON is probably one of the most used serializer, but because of its simplicity, can be slow and can lead to other issues. Indeed, JSON is using a text-like format, and disallow usage of binary in any form - except if they are converted in base64 string for example. Furthermore, JSON does not optimize its payload and does not care by default of the data containing in it.

Today, we will talk a bit of Protocol Buffer or protobuf, a binary serializer format created by Google for their internal use. Instead of JSON, protobuf payload is using a binary format and its data format is specified. One can't add a new field in the payload without having created the specification for it.

Requirements

protoc is required. One can install it from the latest release on Github, or use one's package manager distribution. protoc is used to compile protocol buffer data structure definition in a specific language. In our case, we will need to install an external plugins to help protoc to generate Elixir modules.

$ mix escript.install hex protobuf 0.16.0
...

Bootstrapping

$ mix new pb
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/pb.ex
* creating test
* creating test/test_helper.exs
* creating test/pb_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd pb
    mix test

Run "mix help" for more commands

$ cd pb

$ cat > mix.exs <<EOF
defmodule Pb.MixProject do
  use Mix.Project

  def project do
    [
      app: :pb,
      version: "0.1.0",
      elixir: "~> 1.19",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  def application, do: [extra_applications: [:logger]]

  defp deps, do: [{:protobuf, "~> 0.17.0"}]
end

$ mix deps.get
Resolving Hex dependencies...
Resolution completed in 0.024s
New:
  protobuf 0.17.0
* Getting protobuf (Hex package)
EOF

$ mix escript.install hex protobuf 0.16.0
...

$ export PATH=${PATH}:${HOME}/.mix/escripts

Payload Specification

Let reuse again the rock-paper-scissors idea to design a new protobuf data-structure. The file will be stored in ./proto/v1/rps.proto, but it could be perhaps better to store it in ./priv/proto/v1/rps.proto, not sure yet. Actually, we don't really care for now, because this protocol buffer file will be compiled into Elixir module. The first step is to define the syntax we are using, in our case, proto3.

syntax = "proto3";

Then, we use the package keyword to create a new namespace. In our case, it will create an Elixir module prefixed by Rps.

package rps;

We have 3 shapes to create, an enum should do the job. By convention, the enumerated values should be prefixed to avoid naming conflict. When we will create a new Shape enum, the default value used will be SHAPE_UNKNOWN, because it's the first one defined.

enum Shape {
  SHAPE_UNKNOWN = 0;
  SHAPE_ROCK = 1;
  SHAPE_PAPER = 2;
  SHAPE_SCISSORS = 3;
}

Our second main object we will use is the result of the game. We have 3 values to define, win, draw and loss; they can be defined as another enum following the same previously shown conventions.

enum Result {
  RESULT_UNKNOWN = 0;
  RESULT_WIN = 1;
  RESULT_DRAW = 2;
  RESULT_LOSS = 3;
}

Raw enums are kinda useless without using them inside messages. The first one we can create is the data-structure sent by a player to a server, it will only contain - for now - a Shape. If you are not familiar with the protobuf syntax, like me when I started this publication, the type of the data is on far-left followed by the name of the field. The assignment is not an integer value, but the field number used by the protocol buffer wire format. In this case, the shape field will have the number 1 assigned.

message Play {
  Shape shape = 1;
}

Now, let try to define another data-structure for a player. A player will have an id as integer, and an optional name as string. Protobuf is offering a wide range of scalar types, the best one(s) will mostly depend of our needs.

message Player {
  int64 id = 1;
  optional string name = 2;
}

When a client is asking for an opponent, the servers should return a list of available players. Protocol buffer does not define something like a list of an array, instead, it uses the repeated keyword to create a pseudo-list of objects while encoding or decoding the payload.

message Players {
  repeated Player players = 1;
}

The client select one player from the previous list and start to play with an other player as opponent. The data-structure will then contain a player object and a shape object.

message Play {
  Player player = 1;
  Shape shape = 2;
}

Finally, the server is returning the result, containing an unique id as string, player's informations and the final result for the player. I don't think this is the best data-structure to return because the result can lead to some confusion (who's the winner or loser?) but it will do the job for this example.

message PlayResult {
  string id = 1;
  Player player = 2;
  Player opponent = 3;
  Result result = 4;
}

If everything looks good, we can compile this protocol buffer file into an Elixir module with protoc. It will create the ./lib/proto/v1/rps.pb.ex file.

$ protoc --elixir_out=./lib proto/v1/rps.proto

Let invoke iex to play with these structures. To encode a struct in protobuf, we can use Protobuf.encode/1, it will return a binary. Here few examples from the message specifications defined above.

$ iex -S mix
iex(1)> encoded_player = Protobuf.encode(
  %Rps.Player{
    id: 1,
    name: "test" 
  })
<<8, 1, 18, 4, 116, 101, 115, 116>>

iex(2)> Protobuf.encode(
  %Rps.Player{
    id: 2 
  })
<<8, 2>>

iex(3)> Protobuf.encode(
  %Rps.Players{
    players: []
  })
""

iex(4)> encoded_players = Protobuf.encode(
  %Rps.Players{
    players: [
      %Rps.Player{id: 1},
      %Rps.Player{id: 2, name: "test"}
    ]
  })
<<10, 2, 8, 1, 10, 8, 8, 2, 18, 4, 116, 101, 115, 116>>

iex(5)> encoded_play = Protobuf.encode(
  %Rps.Play{
    player: %Rps.Player{ id: 1},
    shape: 1 
  })
<<10, 2, 8, 1, 16, 1>>

iex(6)> encoded_play = Protobuf.encode(
  %Rps.Play{
    player: %Rps.Player{ id: 1},
    shape: :SHAPE_ROCK
  })
<<10, 2, 8, 1, 16, 1>>

iex(7)> encoded_playresult = Protobuf.encode(
  %Rps.PlayResult{
    id: "random_string",
    result: :RESULT_WIN,
    player: %Rps.Player{id: 1},
    opponent: %Rps.Player{id: 2}
  })
<<10, 13, 114, 97, 110, 100, 111, 109,
  95, 115, 116, 114, 105, 110, 103, 18,
  2, 8, 1, 26, 2, 8, 2, 32, 1>>

When it comes to decode, one can use Protobuf.decode/2 or Protobuf.decode/3. The first argument is the encoded binary and the second is the Elixir module required to decode the payload.

iex(8)> Protobuf.decode(encoded_player, Rps.Player)
%Rps.Player{
  id: 1,
  name: "test",
  __unknown_fields__: [],
  __protobuf__: true
}

iex(9)> Protobuf.decode(encoded_players, Rps.Players)
%Rps.Players{
  players: [
    %Rps.Player{id: 1, name: nil, __unknown_fields__: [], __protobuf__: true},
    %Rps.Player{id: 2, name: "test", __unknown_fields__: [], __protobuf__: true}
  ],
  __unknown_fields__: [],
  __protobuf__: true
}

iex(10)> Protobuf.decode(encoded_playresult, Rps.PlayResult)
%Rps.PlayResult{
  id: "random_string",
  player: %Rps.Player{
    id: 1,
    name: nil,
    __unknown_fields__: [],
    __protobuf__: true
  },
  opponent: %Rps.Player{
    id: 2,
    name: nil,
    __unknown_fields__: [],
    __protobuf__: true
  },
  result: :RESULT_WIN,
  __unknown_fields__: [],
  __protobuf__: true
}

Finally, Here the generated Elixir module by protoc you can find in ./lib/proto/v1/rps.pb.ex:

defmodule Rps.Shape do
  @moduledoc false

  use Protobuf,
    enum: true,
    full_name: "rps.Shape",
    protoc_gen_elixir_version: "0.16.0",
    syntax: :proto3

  field :SHAPE_UNKONWN, 0
  field :SHAPE_ROCK, 1
  field :SHAPE_PAPER, 2
  field :SHAPE_SCISSORS, 3
end

defmodule Rps.Result do
  @moduledoc false

  use Protobuf,
    enum: true,
    full_name: "rps.Result",
    protoc_gen_elixir_version: "0.16.0",
    syntax: :proto3

  field :RESULT_UNKONWN, 0
  field :RESULT_WIN, 1
  field :RESULT_DRAW, 2
  field :RESULT_LOSS, 3
end

defmodule Rps.Player do
  @moduledoc false

  use Protobuf, full_name: "rps.Player", protoc_gen_elixir_version: "0.16.0", syntax: :proto3

  field :id, 1, type: :int64
  field :name, 2, proto3_optional: true, type: :string
end

defmodule Rps.Play do
  @moduledoc false

  use Protobuf, full_name: "rps.Play", protoc_gen_elixir_version: "0.16.0", syntax: :proto3

  field :player, 1, type: Rps.Player
  field :shape, 2, type: Rps.Shape, enum: true
end

defmodule Rps.PlayResult do
  @moduledoc false

  use Protobuf, full_name: "rps.PlayResult", protoc_gen_elixir_version: "0.16.0", syntax: :proto3

  field :id, 1, type: :string
  field :player, 2, type: Rps.Player
  field :opponent, 3, type: Rps.Player
  field :result, 4, type: Rps.Result, enum: true
end

defmodule Rps.Players do
  @moduledoc false

  use Protobuf, full_name: "rps.Players", protoc_gen_elixir_version: "0.16.0", syntax: :proto3

  field :players, 1, repeated: true, type: Rps.Player
end

Layered Design

While doing all those tests, I was thinking if it was a "good practices" or even possible to use protobuf with layers, a bit like a network packet. For example, a first payload is containing a protobuf header with the last part encoded as bytes. This header could then be used to help the decoder to know what kind of data is stored.

package layer;

message header {
  // checksum = "sha256-checksum"
  required string checksum = 1;

  // type = "application/protobuf/players"
  required string type = 2;

  // payload = protobuf binary for players object
  required bytes payload = 3;
}

Let compile it...

$ protoc --elixir_out=./lib/ proto/v1/layer.proto

... And start a new shell to play with that.

iex(1)> encoded_players = Protobuf.encode(%Rps.Players{ players: [%Rps.Player{ id: 1}] })
<<10, 2, 8, 1>>

iex(2)> encoded_headers =  Protobuf.encode(
  %Layer.Header{
    checksum: Base.encode64(
      :crypto.hash(:sha256, encoded_players)
    ),
    type: "application/protobuf/players",
    payload: encoded_players
  })
<<10, 44, 87, 90, 83, 69, 79, 81, 90, 102, 75, 87, 71, 101, 57, 66, 75, 65, 121,
  55, 107, 121, 118, 108, 76, 70, 98, 90, 110, 70, 108, 109, 116, 108, 52, 66,
  69, 83, 79, 102, 67, 89, 117, 43, 56, 61, 18, 28, 97, 112, 112, 108, 105, 99,
  97, 116, 105, 111, 110, 47, 112, 114, 111, 116, 111, 98, 117, 102, 47, 112,
  108, 97, 121, 101, 114, 115, 26, 4, 10, 2, 8, 1>>

With this kind of structure, we can then encapsulate different kind of data without parsing them. In fact, we can also put more metadata in the headers to help the application to know what kind of format is stored in the payload. Even more, one could also add some encryption feature there. Unfortunately, I don't know if it's a good practice, because it can probably make things a bit confusing, but also more flexible. Here the code generated in lib/proto/v1/layer.pb.ex:

defmodule Layer.Header do
  @moduledoc false

  use Protobuf, full_name: "layer.header", protoc_gen_elixir_version: "0.16.0", syntax: :proto2

  field :checksum, 1, required: true, type: :string
  field :type, 2, required: true, type: :string
  field :payload, 3, required: true, type: :bytes
end

Conclusion

This article was just a warmup, a kind of sandbox to see the capabilities of Protocol Buffer. At the same time, I was also looking to the FlatBuffers protocol trying to identify the difference between both format. I would prefer to use CBOR for my projects, but I would also like to avoid using too much dependencies from unknown repositories. Furthermore, protobuf Dart package is already used by Dart and Flutter (for metrics IIRC), it can also be used for messaging as well.

The previous code is containing a lot of design flaws, they can be "easily" fixed by redesigning a bit the data-structures and adding few of them. The procedure should look like that:

  1. A connected client (with an active session) to the server list the available Players;

  2. The client ask the server to create a new Arena for with one available Player;

  3. The server returns an Arena containing an unique identifier, the name of the two players and arena's state (waiting, declined, ready, active, done). A waiting state is when the arena is waiting for the 2 players to become ready. A ready state is when both player are ready and can start playing together. An active state is when both players are playing. A done state is when the game is over, and one player won. A declined state is when the opponent declined the invitation;

  4. When the server is in ready or active state, both players can send their Shape. The server returns a Result. If one win, the Arena's state switch to done.

Designing even a small game is not easy, but it can lead to really interesting result. We have a concrete example of distributed complexity there, with one user sending some data, waiting for result, and one actor (the server) keeping a private state to deal with both users.

Anyway, it was the first article on Protobuf and probably not the last one. I know you would like to dig a bit more on this topic, as usual, a list of resources:

Happy Hack and Have Fun!


Cover Image by Mateusz Szerszyński on Unsplash