r/C_Programming • • Oct 24 '26

I built a zero-dependency concurrent search engine daemon in C11 from scratch (Custom Arena Allocator, SSO, and pthreads).

Hi everyone!

Over the past few weeks, I’ve been working on a lightweight, concurrent text search engine and TCP server built entirely from scratch in pure C11, without any external dependencies.

My main goals were to practice low-level memory management, lock-based concurrency, and custom data structures without relying on heavy frameworks. Here is a quick breakdown of how it's structured:

  • Memory Management: Implemented a custom Arena Allocator to avoid heap fragmentation and handle batch cleanups efficiently.
  • Small String Optimization (SSO): A custom string implementation that stores short strings directly on the stack/struct to minimize heap allocations.
  • Concurrency: Uses POSIX threads (pthread) with read-write locks (pthread_rwlock_t) to allow multiple concurrent readers while safely serializing writes.
  • Persistence: Added a custom zero-overhead binary serialization module (engine_save/engine_load) for instant state restoration from disk.

The project includes a full modular structure (includes/, src/, tests/) and is protected under a source-available license for personal evaluation.

You can check out the source code and architecture details here: 👉 https://github.com/joseramoncabrera/fast-c-search-engine.git

I would love to hear feedback from more experienced C developers here. Specifically:

  1. How do you usually handle edge cases with read-write locks in high-contention search scenarios?
  2. Any architectural improvements you’d suggest for the arena allocator?

Thanks for taking a look!

0 Upvotes

34 comments sorted by

•

u/AutoModerator Oct 24 '26

Hi /u/ConsistentContest256,

Your submission in r/C_Programming was filtered because it links to a git project.

You must edit the submission or respond to this comment with an explanation about how AI was involved in the creation of your project.

While AI-generated code is not disallowed, low-effort "slop" projects may be removed and it's likely that other users push back strongly on substantially AI-generated projects.

You can read more at https://www.reddit.com/r/C_Programming/wiki/index/posting-projects


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

→ More replies (2)

5

u/mikeblas Oct 25 '26 edited Oct 25 '26

All in a single check in?

I'm not sure what this code is meant to do. Can you explain how it runs? What is the engine_test.fa file?

-4

u/ConsistentContest256 Oct 25 '26

"Thanks for pointing that out! Yes, this was an initial dump of a standalone personal project, so it landed in a single commit, but I'll make sure to split future changes into logical commits. Regarding the usage: engine_test.fa is just a sample input/data file for testing the parsing logic. I'll update the README right now with a clear Quickstart guide, compilation commands (gcc), and a breakdown of how the daemon and test files interact."

2

u/mikeblas Oct 25 '26

You sound like an AI. why is that?

1

u/ConsistentContest256 Oct 25 '26

El inglés no es mi idioma nativo: hablo español de forma nativa (si revisas mi repositorio, ¡incluso encontrarás comentarios en español en el código!). Uso herramientas de traducción para pulir mis ideas en inglés y explicar conceptos técnicos de C con claridad. El formato del texto viene de la herramienta de traducción, ¡pero el código en C, la gestión de memoria y la lógica están 100% hechos a mano por mí

1

u/mikeblas Oct 25 '26

Thank you for explaining that -- I thought it might be the case. Might be best to explain that when you post. Otherwise, people will jump to the conclusion that you are a robot. Some people just post in their native language and let the reader translate, using either their favorite translation tool or Reddit's built-in translators.

2

u/ConsistentContest256 Oct 26 '26

Tiene todo el sentido del mundo, ¡gracias por el consejo! Definitivamente añadiré una nota en futuras publicaciones para que no haya malentendidos. Agradezco la retroalimentación constructiva

1

u/mikeblas Oct 26 '26

Good luck!

5

u/Limp-Confidence5612 Oct 25 '26

Since your arenas are static and do not grow, why even use arenas and not just allocate arrays of the appropriate size directly?

Using malloc for it is the second thing. I would recommend you look directly into mmap() and use it to allocate virtual address space that only gets allocated when you actually touch a page.

-5

u/ConsistentContest256 Oct 25 '26

"Thanks for the feedback! You're completely right about mmap()—moving towards a virtual memory-backed arena using mmap with anonymous pages is definitely on the roadmap for a future iteration to handle demand paging better. Regarding the arena vs. raw arrays: even if the size is fixed, the arena pattern allows me to hand out sequential pointers instantly via a bump-pointer with zero per-allocation metadata overhead, and reset/free everything in a single bulk operation, which raw arrays don't handle as cleanly for dynamic-lifetime chunks within the same execution block."

2

u/Limp-Confidence5612 Oct 25 '26 edited Oct 25 '26

What I'm saying is that since you're not actually doing any dynamic allocation, you do not need the arena at all. A statically sized array would do exactly the same, and you can track them the same way. What downside do you see there?

One thing I do with my arenas, I keep the first element of the arena zero initialized and use it in failure cases.

1

u/ConsistentContest256 Oct 25 '26

That's a fair question! While under the hood both rely on a contiguous block of memory, wrapping it as an Arena abstraction gives me a clean state manager rather than relying on raw global/static arrays. It encapsulates the bump offset and capacity, allows me to reset the entire memory state in $O(1)$ by just resetting the offset, and makes it easy to instantiate separate local arena instances (e.g., per-thread or per-request scope) using the same allocator API.

Also, keeping index 0 zero-initialized for graceful fallback handling is a fantastic pattern! I hadn't considered using it as a safe null-like sentinel for failed allocations in this implementation. I'll definitely experiment with that to make allocation failures even safer. Thanks for sharing that trick

1

u/Limp-Confidence5612 Oct 25 '26

It's still o(1) with the static array approach. You also just reset an offset. I know arenas are cool, a r I like to shoehorn them into many things I do, but don't do it just because. If you need dynamic allocations it makes sense, but if you know beforehand how big your data is, there is no need.

1

u/[deleted] Oct 25 '26

[removed] — view removed comment

1

u/ConsistentContest256 Oct 25 '26

«¡Gracias! De verdad aprecio que te tomaras el tiempo de revisar el código. Tus comentarios sobre mmap() me dieron mucho en qué pensar, y definitivamente aplicaré esos conocimientos a medida que siga mejorando el motor. ¡Gracias de nuevo!»

0

u/ConsistentContest256 Oct 25 '26

Thank you! I really appreciate you taking the time to review the codebase. Your feedback on mmap() gave me a lot to think about, and I'll definitely be applying those insights as I keep improving the engine. Thanks again!

5

u/floatfloatjam Oct 25 '26

Your AI slop has no power here

-5

u/ConsistentContest256 Oct 25 '26

Fair enough! But if you dig into the code, you'll see it's pure handcrafted C11. No black-box frameworks, just a custom arena bump-pointer allocator, manual pthread_rwlock_t sync, and custom SSO strings. Run it under Valgrind—it's leak-free.

Honestly, I really appreciate the comments here because they've already pointed out real design flaws in my approach. Ironically, if an AI had just generated this, those very human design mistakes probably wouldn't exist—they are part of my own learning process.

I’ve been studying C on my own for 2 years. For a long time, I always thought I had to "know everything" before I could build a real system from scratch. I finally decided to just dive in, and it made me realize that you don't need to wait until you're a senior dev to start building things.

Feel free to roast the implementation details if you spot any other bugs!

3

u/vitamin_CPP Oct 25 '26

Do you often use emdash when writing in forums?

1

u/ConsistentContest256 Oct 25 '26

Good catch! English is not my native language (Spanish is)—as you can probably tell from my comments in Spanish—so I use translation tools to polish my responses and communicate clearly in English. But the C code, architecture, and memory headaches are 100% mine!

3

u/vitamin_CPP Oct 25 '26

dude. This must be rage bate.

1

u/ConsistentContest256 Oct 26 '26

It's not. It's just my first real C project and I made design mistakes while learning. I'm taking the technical feedback and fixing the issues

1

u/floatfloatjam Oct 26 '26

In that case, I apologize for being so harsh. It is, however, bad form to pass off AI work as your own. Whats the point, anyway?

1

u/ConsistentContest256 Oct 26 '26

Apology accepted. I wrote this code myself while learning and working through these low-level concepts, so I appreciate feedback on the actual implementation.

1

u/TheChief275 Oct 25 '26

I don't get the point of having both arena allocators as well as SSO? The point of SSO is not necessarily reducing allocations but more that standard allocators often have a big required size of allocation (32 bytes or even more), as well as allocation and deallocation time and cost being unpredictable. If you're using arena allocators and still use SSO, you lose all the arena benefits regarding strings, which is that you only need ptr+length, and that every string will look and behave the same regardless of whether it is static memory or allocated. With arenas, the allocation + deallocation cost is bar to none and above all predictable. There's more benefits but there's honestly too many to mention here

1

u/ConsistentContest256 Oct 25 '26

"That's a very fair point and a great architectural observation! You're absolutely right that in a pure arena-backed system, the traditional performance penalty of malloc disappears, making a simple ptr + length slice model extremely predictable and clean.

My reasoning for keeping SSO alongside the arena was mostly to minimize memory footprint and bump-allocations within the arena itself for high volumes of very short tokens (like terms, tags, or small identifiers). By keeping short strings embedded directly inside the string header struct (e.g., on the stack or inline array), I avoid touching or advancing the arena's bump pointer entirely for those small allocations, reserving the arena capacity strictly for larger text blocks.

1

u/TheChief275 Oct 25 '26

...and in turn you add a whole lot of SSO overhead. I've implemented it myself before and it definitely isn't free. Basically every function requires branching for layout.

Also, why are you giving LLM generated responses? Is this your comments literally translated or did you just ask ChatGPT to respond? It makes people legitimately doubtful of whether your codebase was actually handwritten, which you claim

1

u/ConsistentContest256 Oct 26 '26

**You bring up a valid technical point about SSO. The branching logic (**if/else checks for short vs. heap layouts) is indeed a performance trade-off to avoid heap allocations, and managing that complexity is one of the main things I'm refining in this project.

As for my response: I write my thoughts in Spanish and use AI strictly to translate them into clear English, since it's not my primary language. I can assure you the codebase was 100% written by me by hand—which is why it has all the learning mistakes and design flaws mentioned in this thread! Thanks for the technical insight on the branching overhead.

1

u/vitamin_CPP Oct 25 '26

Are you a bot, or just a meat proxy?

2

u/ConsistentContest256 Oct 25 '26

100% meat proxy, powered by coffee and two years of self-taught C debugging headaches.

2

u/zellforte Oct 26 '26

>A custom string implementation that stores short strings directly on the stack/struct to minimize heap allocations.

struct String{
char *data;
char sso[SSO + 1];
size_t size;
size_t capacity;
};

String *string_create(void){
String *s = malloc(sizeof *s);
//...
return s;
}

This is pure nonsense, upgrade your AI model or provide better prompts.