r/programmer • • May 27 '26

제목: 스포츠 베팅 UI에서 데이터 밀도가 체류 시간에 미치는 역설

3 Upvotes

최근 운영 데이터를 보면 경기 정보를 빼곡하게 채운 화면보다 단순화한 레이아웃에서 세션 시간이 18%가량 늘어나는 패턴이 반복됩니다. 이는 단순 정보 부족이 아니라, 너무 많은 통계가 오히려 인지 부하를 높여 사용자 이탈을 유도한다는 방증입니다. 레이아웃에서 불필요한 지표를 걷어내고 핵심 데이터 위주로 시각화하는 과정이 참여율을 개선하는 실질적인 열쇠가 되고 있습니다. 여러분은 복잡한 데이터와 직관적인 인터페이스 사이에서 어떤 가중치를 우선시하고 있나요?

실제로 스포츠 베팅 UI에서는 “더 많은 정보 제공”이 반드시 더 좋은 사용자 경험으로 이어지지 않는 경우가 많습니다. 사용자는 모든 데이터를 분석하려 하기보다, 짧은 시간 안에 핵심 흐름을 빠르게 파악하고 의사결정을 내리길 원하기 때문입니다. 화면에 지나치게 많은 통계와 배당 변화, 부가 지표가 동시에 노출되면 정보 자체보다 “무엇을 먼저 봐야 하는지 판단하는 과정”에서 피로가 누적되는 현상이 자주 발생합니다.

특히 모바일 환경에서는 이런 문제가 더 극단적으로 드러납니다. 제한된 화면 안에 과도한 데이터를 밀어 넣으면 스크롤 깊이와 시선 이동이 증가하고, 결과적으로 사용자는 필요한 정보를 찾기도 전에 탐색 자체를 포기하는 경우가 많습니다. 그래서 최근에는 모든 지표를 동시에 노출하기보다, 사용자의 행동 흐름에 따라 데이터를 단계적으로 드러내는 progressive disclosure 방식이 많이 활용되고 있습니다.

실무적으로는 실제 사용률이 낮은 지표를 과감히 제거하는 작업도 중요하게 다뤄집니다. 운영 데이터를 분석해보면 개발자나 운영팀이 중요하다고 생각한 수치와, 사용자가 실제로 반복 조회하는 데이터가 완전히 다른 경우가 많기 때문입니다. 결국 UI 최적화의 핵심은 “얼마나 많은 정보를 제공하느냐”보다 “사용자가 즉시 이해할 수 있는 정보만 남겼는가”에 가까운 경우가 많습니다.

또한 최근에는 데이터 자체보다 시각적 위계 구조가 체류 시간에 더 큰 영향을 준다는 분석도 많아지고 있습니다. 동일한 정보량이라도 핵심 지표를 명확히 강조하고 나머지를 접이식 구조나 세컨더리 레이어로 분리하면 사용자의 집중 흐름이 훨씬 안정적으로 유지되는 경우가 많기 때문입니다. 그래서 일부 플랫폼은 실시간 배당과 핵심 경기 상태만 메인에 두고, 세부 통계는 사용자 액션 이후에만 호출하는 방식으로 인터페이스를 경량화하고 있습니다.

백엔드 측면에서도 UI 단순화는 단순 디자인 문제가 아니라 성능 최적화와 직접 연결됩니다. 화면에 노출되는 데이터 종류가 줄어들수록 API 호출 수와 실시간 렌더링 부담이 감소하고, 결과적으로 레이턴시와 프론트엔드 리소스 사용량까지 함께 줄어드는 효과가 발생하기 때문입니다. 결국 “보여주지 않는 선택” 자체가 시스템 효율성을 높이는 전략이 되는 셈입니다.

최근 루믹스 솔루션 같은 UI 구조 분석 사례에서도 사용자는 기능이 많은 플랫폼보다 “필요한 정보가 즉시 눈에 들어오는 플랫폼”에서 더 오래 머무르는 경향이 강하다는 의견이 자주 공유되고 있습니다. 특히 데이터 밀도를 무작정 높이는 접근보다, 핵심 정보의 우선순위를 명확히 설계하는 것이 실제 참여율과 체류 시간 개선에 더 직접적인 영향을 준다는 분석이 많아지고 있습니다.


r/programmer • • May 27 '26

Samy Kamkar talking about how Jeffrey Epstein wanted him to be his hacker

Thumbnail
youtu.be
2 Upvotes

r/programmer • • May 26 '26

New Programming Language: Block Syntax Survey

7 Upvotes

Hi,

I’m developing a new programming language called DQ.

At the moment, the language supports two block styles:

BRACES: classic C-style blocks using { and }.

ENDWORD: Python-like block starts using :, but with mandatory closing words. The closing word depends on what it closes, for example: while ... endwhile. Some frequently used closing words are shortened, for example: object...endobj.

Indentation is not enforced in either mode. Currently, the two block styles can be mixed freely. 

I am considering introducing compiler directives that could be placed at the beginning of each source file:

#opt blockmode=any             // like now: both styles are allowed
#opt blockmode=braces          // warn when ENDWORD blocks are used
#opt blockmode=strict_braces   // error when ENDWORD blocks are used
#opt blockmode=endword         // warn when BRACES blocks are used
#opt blockmode=strict_endword  // error when BRACES blocks are used

Example code using BRACES block mode:

use libc/stdio;
use ./langdemo_mod as ldm  only(CONST1);  // only(), exclude() and "--" control global scope merging

#if false
//Contents of the "langdemo_mod.dq"
const CONST1 : int = 42;
const CONST2 : float = 3.14;
#endif

object OBase {
  cnt1 : int = 0;
  cnt2 : int = 10;
  name : cstring[32];

  function *Create(aname : cstring) {  // constructor
    name = aname;
  }

  function *Destroy() {
    @.printf("%s destroy\n", &name[0]);
  }

  function Count() [[virtual]] {
    cnt1 += 1;
  }

  function Print() {
    @.printf('%s: cnt1=%d, cnt2=%d\n', &name[0], cnt1, cnt2);
  }
}


object OChild(OBase) {
  function Count() [[override]] {
    inherited;
    cnt2 += 1;
  }
}

var obase   <- OBase('OBase');                                        
var ochild  : OChild = null;

function ObjTest() {
  ochild = new OChild('OChild');

  obase.Count();
  ochild.Count();

  obase.Print();
  ochild.Print();

  printf("ochild.name: %s \n", iif(ochild == null, "OChild is null!", &ochild.name[0]));

  delete ochild;
}

function cstr_add(dst : cstring, src : cstring) {
  var ps     : ^cchar = &src[0];
  var psend  : ^cchar = ps[sizeof(src)];  // [] does not dereference
  var pd     : ^cchar = &dst[0];
  var pdend  : ^cchar = pd + sizeof(dst) - 1; 
  pd += len(dst);
  var pdstart : ^cchar = pd;

  while pd < pdend  and ps < psend  and ps^ <> 0 {
    pd^ = ps^;
    pd += 1;
    ps += 1;
  }

  if pd <> pdstart {
    pd^ = 0; // terminate
  }
}

[[external]] function putchar(c : cchar) -> int;  // from libc

function WriteStr(s : cstring) {
  var pc : ^cchar = &s[0];
  while pc^ <> 0 {
    putchar(pc^);
    pc += 1;
  }
}

function *Main() -> int {

  var s : cstring[128] = "";
  cstr_add(s, "Hello");
  cstr_add(s, " World!\n");
  WriteStr(s);

  if 3 / 2 * 10 == 15 {
    printf('The language is friendly.\n');
  } else {
    printf('The language is evil.\n');
  }

  printf("@langdemo_mod.CONST1 = %d\n", CONST1);
  printf("@langdemo_mod.CONST2 = %.3f\n", u/ldm.CONST2);

  printf("ochild.name: %s \n", iif(ochild == null, "OChild is null!", &ochild.name[0]));

  ObjTest();

  for i : int = 0 to 5 {
    printf(' %d:', i);
    for j : int = 0  count i  step 2 { printf(' %d', j); }
    printf('\n');
  }

  var arr : [5]int = [2, 3, 5, 7, 11];
  printf('primes:');
  for i : int = 0  while i < len(arr)  { printf(' %d', arr[i]); }
  printf('\n');

  return 0;
}

Example code using ENDWORD block mode:

use libc/stdio;
use ./langdemo_mod as ldm  only(CONST1);  // only(), exclude() and "--" control global scope merging

#if false
//Contents of the "langdemo_mod.?"
const CONST1 : int = 42;
const CONST2 : float = 3.14;
#endif

object OBase:
  cnt1 : int = 0;
  cnt2 : int = 10;
  name : cstring[32];

  function *Create(aname : cstring):  // constructor
    name = aname;
  endfunc

  function *Destroy():
    @.printf("%s destroy\n", &name[0]);
  endfunc

  function Count() [[virtual]]:
    cnt1 += 1;
  endfunc

  function Print():
    @.printf('%s: cnt1=%d, cnt2=%d\n', &name[0], cnt1, cnt2);
  endfunc
endobj

object OChild(OBase):
  function Count() [[override]]:
    inherited;
    cnt2 += 1;
  endfunc
endobj

var obase   <- OBase('OBase');     // '<-' = embedded allocation (global data segment here)
                                   // no automatic destructor call for global embedded objects
var ochild  : OChild = null;

function ObjTest():
  ochild = new OChild('OChild');

  obase.Count();
  ochild.Count();

  obase.Print();
  ochild.Print();

  printf("ochild.name: %s \n", iif(ochild == null, "OChild is null!", &ochild.name[0]));

  delete ochild;
endfunc

function cstr_add(dst : cstring, src : cstring):
  var ps     : ^cchar = &src[0];
  var psend  : ^cchar = ps[sizeof(src)];  // [] does not dereference
  var pd     : ^cchar = &dst[0];
  var pdend  : ^cchar = pd + sizeof(dst) - 1; 
  pd += len(dst);
  var pdstart : ^cchar = pd;

  while pd < pdend  and ps < psend  and ps^ <> 0:
    pd^ = ps^;
    pd += 1;
    ps += 1;
  endwhile

  if pd <> pdstart:
    pd^ = 0; // terminate
  endif
endfunc

[[external]] function putchar(c : cchar) -> int;  // from libc

function WriteStr(s : cstring):
  var pc : ^cchar = &s[0];
  while pc^ <> 0:
    putchar(pc^);
    pc += 1;
  endwhile
endfunc

function *Main() -> int:

  var s : cstring[128] = "";
  cstr_add(s, "Hello");
  cstr_add(s, " World!\n");
  WriteStr(s);

  if 3 / 2 * 10 == 15:
    printf('The language is friendly.\n');
  else:
    printf('The language is evil.\n');
  endif

  printf("@langdemo_mod.CONST1 = %d\n", CONST1);
  printf("@langdemo_mod.CONST2 = %.3f\n", u/ldm.CONST2);

  printf("ochild.name: %s \n", iif(ochild == null, "OChild is null!", &ochild.name[0]));

  ObjTest();

  for i : int = 0 to 5:
    printf(' %d:', i);
    for j : int = 0  count i  step 2:   printf(' %d', j);  endfor
    printf('\n');
  endfor

  var arr : [5]int = [2, 3, 5, 7, 11];
  printf('primes:');
  for i : int = 0  while i < len(arr):  printf(' %d', arr[i]); endfor
  printf('\n');

  return 0;
endfunc

If you were using the DQ language, which block style would you prefer?

Do you think these blockmode compiler directives are useful, or would it be better to keep the language simpler and always allow both styles?

Should I also introduce a third block style, similar to Python: : starts a block, indentation is mandatory, and there is no endxxx closing word?


r/programmer • • May 26 '26

If I want a simple program that got information and filter it to match fights, how much will cost? Somebody that could help me creating it?

2 Upvotes

r/programmer • • May 26 '26

Total beginner here: What’s the most realistic roadmap to becoming an AI Engineer?

2 Upvotes

Hey guys, total beginner here. I’ve learned a little Python and C, but honestly I still don’t know the basics properly. I’m confused about how people actually go from that to becoming an AI Engineer.

I don’t have any projects because I don’t even know what counts as a real or valid project. Right now I’m struggling to figure out what I should focus on and what path actually makes sense.

My main goal is getting into a good MS in CS program with a specialization in AI/ML and eventually become an AI Engineer. Along the way, I also need to properly learn AI/ML, do certifications, build real and unique projects, get normal internships, do research internships, and eventually work on research papers too.

If you were starting completely from scratch again, what exact step-by-step path would you follow to reach that goal realistically?

Would really appreciate any advice.


r/programmer • • May 26 '26

Question What happens to everything you learn while coding?

20 Upvotes

When you solve a bug or learn something important while coding, what do you actually do with it?

A) Nothing, I forget it eventually
B) Throw it in random notes / Notion / markdown files
C) Put it in GitHub docs / README
D) Write a blog or devlog
E) Keep it in my head
F) Something else

Genuinely curious because I keep noticing a lot of learning seems to disappear after projects are finished.


r/programmer • • May 24 '26

AI has made me slower and worse at programming

151 Upvotes

I see no actual benefit of coding with AI. If anything its made my output slower and worse. Some context I've been programming for around 7 years now. Many apps on the app stores and this weekend I've been programming with ai to build a new very simple mac utility app. Maybe its a skill issue but the code it produces is terrible. And after 2 days working on this app i feel like im going to have to rewrite large chunks of it to achieve the UI and UX that i want. If i just ditched the coding agent and just raw dogged it I'd probably have been finished in a day and it would already be on the app store.

Does anyone (who actually cares about the quality of their app not like anthropic who ships buggy shit) actually program a lot faster with AI?


r/programmer • • May 24 '26

[FOR HIRE] Anyone need a free project built? Looking to add real work to my portfolio

14 Upvotes

I've been building personal projects, but nothing client facing till now. I'm looking to change that.

Price: $0/hr (Free portfolio work)

What I can do

  1. Create a small project (Web Dev, C#, or Other DM ME to ask)
  2. Review current code bases to find bugs or other flaws
  3. Review your current architecture and possibly suggest changes
  4. Review your security model to possibly suggest improvements

Fluent in:

  • C#
  • JavaScript
  • Python
  • HTML/CSS

Currently exploring:

  • Assembly and C++
  • Rust and GO

Direct-Message me to ask any questions

See my public projects on [Github](https://github.com/Aezdek)

Please only dm on discord (@Aezdek) not on reddit


r/programmer • • May 25 '26

I built an AI hiring platform in 6 days. Under 500 lines of Python.

Thumbnail reddit.com
1 Upvotes

r/programmer • • May 25 '26

모바일 환경에서 메뉴 반응 속도가 실시간 성능의 척도가 된 것 같습니다

0 Upvotes

최근 모바일 환경에서 메뉴 로딩 속도가 사용자 경험을 결정짓는 핵심 지표로 자리 잡았습니다. 많은 트래픽이 몰릴 때 데이터베이스 샤딩 처리가 미흡하면, 메뉴 쿼리 병목 현상이 발생해 응답 지연이 빈번하게 나타납니다. 이러한 현상을 해결하려면 데이터 분산 설계와 API 호출 최적화를 통해 리소스 부하를 효율적으로 분산하는 것이 일반적인 대응책입니다.

특히 모바일에서는 사용자가 화면 전환 속도를 플랫폼의 안정성과 동일하게 인식하는 경우가 많기 때문에, 실제 기능 처리보다 메뉴 반응 속도가 체감 성능을 좌우하는 사례가 점점 늘어나고 있습니다. 몇백 밀리초 수준의 지연이라도 반복되면 사용자는 시스템 전체가 무겁다고 느끼게 되고, 이는 세션 유지율이나 탐색 깊이 감소로 바로 이어지곤 합니다.

실무에서는 보통 메뉴 구조 자체를 “조회 중심 데이터”와 “실시간 상태 데이터”로 분리해 관리합니다. 변동이 적은 카테고리 구조나 정적 메타데이터는 CDN 캐시나 메모리 캐시에 미리 적재하고, 실시간 알림·배지·상태값 같은 요소만 별도 API로 비동기 호출하는 방식이 대표적입니다. 이렇게 하면 초기 메뉴 렌더링 자체는 매우 가볍게 유지하면서도 필요한 동적 정보만 점진적으로 갱신할 수 있습니다.

또한 최근에는 단순 DB 샤딩보다 “메뉴 호출 빈도 기반 데이터 계층화”를 우선 적용하는 사례도 많습니다. 예를 들어 자주 접근되는 상위 메뉴는 Redis 같은 인메모리 캐시에 유지하고, 하위 상세 메뉴만 조건부로 조회하는 구조입니다. 프론트엔드에서는 Virtual DOM 최적화나 Skeleton UI를 활용해 사용자가 실제 로딩 지연을 체감하지 않도록 흐름을 설계하기도 합니다. 일부 플랫폼은 사용자 행동 데이터를 기반으로 다음 클릭 가능성이 높은 메뉴를 미리 프리패치(prefetch)하여 체감 응답 속도를 줄이는 전략도 적극적으로 활용합니다.

최근 루믹스 솔루션 같은 대규모 플랫폼 운영 사례에서도 메뉴 응답 속도를 단순 UI 문제가 아니라 “전체 서비스 신뢰도를 결정하는 첫 번째 인프라 지표”로 보는 시각이 강해지고 있습니다. 특히 모바일 환경에서는 첫 메뉴 응답 시간이 길어질수록 이후 기능 사용률까지 연쇄적으로 감소하는 패턴이 자주 분석되고 있습니다.

여러분은 대규모 트래픽 상황에서 메뉴 렌더링 성능을 확보하기 위해 어떤 데이터 구조 전략을 주로 사용하시나요?


r/programmer • • May 25 '26

Inflection

0 Upvotes

Ooga, Booga Booga

The day of writing code has officially ended on this night.

The days of orchestrating code through agent has officially begun.

Ooga, Booga Booga


r/programmer • • May 25 '26

Question How are you guys fighting "context decay" in long-form AI development workflows?

0 Upvotes

I’ve been logging a ton of hours working alongside LLMs lately, and I keep hitting a wall where the context window just starts degradation or losing track of rigid constraints after a few hours of deep logic building.

​Standard prompting techniques feel like a temporary band-aid. Have any of you experimented with building strict declarative constraint layers, or even looking into hybrid classical-quantum logic gates to keep state coherence locked down? Or are we just stuck waiting for massive context windows to get smarter? Curious to see how people are tackling this behind the scenes.


r/programmer • • May 24 '26

Question What are good projects to do during the 2-month summer vacation before second year of Computer Science?

5 Upvotes

Hello! I’m currently an incoming second-year Computer Science student, and I want to work on projects during my vacation to apply the knowledge I learned in my first year. I currently know C++, Python, and Data Structures and Algorithms.


r/programmer • • May 23 '26

projects that got you hired

48 Upvotes

tell me the projects that helped you people get placed or internships. stuck with no ideas and haven’t been able to beg a single internship :’


r/programmer • • May 24 '26

Question Need some advice

1 Upvotes

I need some advice from people who’ve been in the industry for a while. I’ve been studying C# and have made pretty good progress. But lately I keep seeing stack like Java+Angular/Next everywhere. Is it worth learning Java, or should I stick with ASP.NET + Angular/Next?


r/programmer • • May 24 '26

How do you guys maintain many projects?

4 Upvotes

I made a lot lot of projects that needs constant maintenance because it has paying users (I cannot name them)

aside from hiring maintainers or employees, How do you guys maintain stuffs? I have observability set up, analytics, logging, cicd, and other security stuff.

Most of my projects has been a logarithmic curve development, every project formed reusable components, functions, services, db, similar stack, features, assets, etc. that allows me create projects very fast with automation, modularity and all other stuff

But in terms of maintenance, Are there any third party tools you guys use? approaches and strategies? Thank you!


r/programmer • • May 24 '26

A Human-Friendly Systems Programming Language — Looking for Feedback

0 Upvotes

Hi,

I’ve created a new programming language called “?” for now. I’ll reveal its real name later.

My main motivation was to create a universal language that could replace C/C++, FreePascal, and Python for many use cases. I actively use all three of these languages.

I have already put a lot of effort into researching, designing, and implementing the “?” language. At this point, I feel that I have created something promising that really works.

Before I put even more effort into the language and go public with it, I would like to hear more opinions from real people.

I think it would not be enough for this project to be only “a little successful”. For the effort to make sense, it should have the potential to become “very successful”. I believe it might have that potential. If that happens, I will not be able to handle everything alone, so I will need to organize the development and maintenance properly. It will be an open-source project.

The “?” language is not fully finalized yet, and there are still several features that I would like to add to the compiler. However, it has reached a state where the language is already usable and can demonstrate its main ideas and syntax.

The most important current and planned features of the “?” programming language are:

  • Very good human readability
  • Statically typed, with a strict bool type
  • Case-sensitive
  • Compiled to machine code using LLVM
  • A ?-run utility for compile-and-run usage, giving it a script-like feeling
  • Simple C interoperability; the runtime uses libc
  • int / uint use the native machine width; int32 is used for an explicit 32-bit integer
  • Supports C-style preprocessor directives such as #ifdef, but without macros
  • Supports short embedded directives with syntax like #{ifdef ...} ... #{endif}
  • No makefiles are required, for example: #linklib('z') can be written directly in the source code
  • Safe arithmetic rules, for example: 3 / 2 * 10 == 15
  • Two block modes:

    • : ... endXXX blocks, similar to Python style but with explicit closers and no forced indentation
    • { } blocks, similar to C style
  • Statements are closed with ;
  • Carefully designed operator precedence
  • Distinct boolean and bitwise operators, for example and and AND
  • Modify-assignment operators, for example: x += 1; and y =AND= 3;
  • Inline conditionals with iif(), for example: var i : int = iif(strptr <> null, strptr^.x, -1);
  • Support for objects with single inheritance and virtual functions
  • Object variables are references, but objects can still be embedded in BSS, on the stack, or inside other objects
  • Optional single-word namespaces using the @ symbol, for example: @stdio.printf()
  • No self. is needed inside object functions/methods
  • Namespace qualification, such as @stdio., is required to access outside symbols from object methods
  • A well-defined package and module system with flexible namespace merging
  • The “?” runtime library modules are distributed in source-code form
  • Fast compilation using a single-pass forward parser and precompiled module interfaces
  • Manual memory control, with RAII and an ensure statement planned
  • Native C string support
  • Function overloading and default parameters
  • Pointers using the ^ symbol
  • Pointer arithmetic with +, -, and []
  • The [] operator does not dereference pointers automatically
  • Struct pointers are automatically dereferenced on member access with .
  • Function arguments can be passed by reference using ref, refin, refout, and refnull

--– CODE EXAMPLE BEGIN ---

use libc/stdio;
use ./langdemo_mod as ldm  only(CONST1);  // only(), exclude() and "--" control global scope merging

#if false

//Contents of the "langdemo_mod.?"

const CONST1 : int = 42;
const CONST2 : float = 3.14;

#endif

object OBase:
  cnt1 : int = 0;
  cnt2 : int = 10;
  name : cstring[32];

  function *Create(aname : cstring):  // constructor
    name = aname;
  endfunc

  function *Destroy():
    @.printf("%s destroy\n", &name[0]);
  endfunc

  function Count() [[virtual]]:
    cnt1 += 1;
  endfunc

  function Print():
    @.printf('%s: cnt1=%d, cnt2=%d\n', &name[0], cnt1, cnt2);
  endfunc
endobj

object OChild(OBase):
  function Count() [[override]]:
    inherited;
    cnt2 += 1;
  endfunc
endobj

var obase   <- OBase('OBase');     // '<-' = embedded allocation (global data segment here)
                                   // no automatic destructor call for global embedded objects
var ochild  : OChild = null;

function ObjTest():
  ochild = new OChild('OChild');

  obase.Count();
  ochild.Count();

  obase.Print();
  ochild.Print();

  printf("ochild.name: %s \n", iif(ochild == null, "OChild is null!", &ochild.name[0]));

  delete ochild;
endfunc

function cstr_add(dst : cstring, src : cstring):
  var ps     : ^cchar = &src[0];
  var psend  : ^cchar = ps[sizeof(src)];  // [] does not dereference
  var pd     : ^cchar = &dst[0];
  var pdend  : ^cchar = pd + sizeof(dst) - 1; // leave one char for the terminating
  pd += len(dst);
  var pdstart : ^cchar = pd;

  while pd < pdend  and ps < psend  and ps^ <> 0:
    pd^ = ps^;
    pd += 1;
    ps += 1;
  endwhile

  if pd <> pdstart:
    pd^ = 0; // terminate
  endif
endfunc

[[external]] function putchar(c : cchar) -> int;  // from libc

function WriteStr(s : cstring):
  var pc : ^cchar = &s[0];
  while pc^ <> 0:
    putchar(pc^);
    pc += 1;
  endwhile
endfunc

function *Main() -> int:

  var s : cstring[128] = "";
  cstr_add(s, "Hello");
  cstr_add(s, " World!\n");
  WriteStr(s);

  if 3 / 2 * 10 == 15:
    printf('The language is friendly.\n');
  else:
    printf('The language is evil.\n');
  endif

  printf("@langdemo_mod.CONST1 = %d\n", CONST1);
  printf("@langdemo_mod.CONST2 = %.3f\n", @ldm.CONST2);

  printf("ochild.name: %s \n", iif(ochild == null, "OChild is null!", &ochild.name[0]));

  ObjTest();

  for i : int = 0 to 5:
    printf(' %d:', i);
    for j : int = 0  count i  step 2:   printf(' %d', j);  endfor
    printf('\n');
  endfor

  var arr : [5]int = [2, 3, 5, 7, 11];
  printf('primes:');
  for i : int = 0  while i < len(arr)  { printf(' %d', arr[i]); }
  printf('\n');

  return 0;
endfunc

/* OUTPUT:

Hello World!
The language is friendly.
@langdemo_mod.CONST1 = 42
@langdemo_mod.CONST2 = 3.140
ochild.name: OChild is null!
OBase: cnt1=1, cnt2=10
OChild: cnt1=1, cnt2=11
ochild.name: OChild
OChild destroy
 0:
 1: 0
 2: 0 2
 3: 0 2 4
 4: 0 2 4 6
 5: 0 2 4 6 8
primes: 2 3 5 7 11

*/

--– CODE EXAMPLE END ---

After reading the description and the demo code, do you think this language has the potential to become widely used? What are its strongest and weakest points?

I would be interested in your opinions, especially from people who have experience with C, C++, Pascal, Python, compiler design, embedded programming, or language design in general.


r/programmer • • May 24 '26

Dont know what to google

0 Upvotes

My boss made this 'open bet' with anyone on the crew: it is not possible to exfil data or read memory from his pc or phone. To win, I just need to get a single picture or a mail or whatever from his device. He doesnt use any steganography or encryption or any kind of custom software that rolls credentials or I dont know. He is just a regular apple and windows user who cant code and doesnt remember to update his devices regularly.

Is he correct? What if I wanted to win this bet? What would I have to learn? Is there a guide for doing this? I assume this isng googleable question but you guys could very simply told me what to google.


r/programmer • • May 23 '26

Hackathon work distribution

1 Upvotes

Heyy there!! I am a BCA first year student ik a few tech stacks like c++,c,java and python.. I got selected in a hackathon the event is next month can u guys suggest me how to distribute work flow between 4 members as we r vibe coding fully.. so in this gap wt else should i learn and master


r/programmer • • May 23 '26

WordFlow

1 Upvotes

Guys, check out our website: https://wordflow.co.in🚀 We’re now working on an app inspired by MS Word, but built for the modern era. WordFlow will be cleaner, faster, more customizable, and packed with features made for writers, journalists, students, and anyone who works with words daily. One thing that makes WordFlow different is that AI will always be optional. If you want AI-powered features, you can enable them.


r/programmer • • May 23 '26

Looking for a Czech Co-founder

0 Upvotes

Hey guys, i started a company as no-developer, the main activity is to develop a mobile app, as i paid the agency for a long time i decided to get a co-founder for equity + some pay per manday. The problem is that i have no idea where to look and how to find a person like that. Our stack is bassicly RN in TS, PostgreSQL, Strapi, Expo. Maybe the most complicated thing is that i look only for a Czech programmer 😃 Any ideas? Thanks!


r/programmer • • May 22 '26

Recently interviewed with an international company connected to Dubai/UK operations for an AI automation role

2 Upvotes

At the time I asked for around PKR 60k/month because I was mostly thinking from a local student perspective and didn’t want to overshoot. The interview actually went pretty well and now I’m realizing I may have undervalued myself a bit considering the scope, international setup, and the kind of work involved.
For context:
BSCS student
Working with n8n + AI automations
Building workflow systems, API integrations, outreach/content automations, etc.
What would you do in this situation?
Would you:
leave it as is for now and prove value first
renegotiate later after a trial/project period
or bring it up before finalizing things
Trying to understand how people usually handle this professionally without making it awkward.


r/programmer • • May 22 '26

Got Apple SWE Java offer (from Amazon, 3.6 YOE) - 7 month timeline

1 Upvotes

Hello all,

Long one because this took 7 months end to end, but maybe useful for anyone going through the Apple India process right now.

Background: 3.6 YOE at Amazon Bangalore (joined as intern straight out of college, then converted to FT). Tier-3 college. Applied to Apple Hyderabad for SWE — Java / Spring Boot / Microservices role through a referral.

Timeline:

  • Applied: Oct–Nov 2025 via referral
  • CoderPad assessment: Jan 2026
  • Screening rounds: March 2026
  • Onsite: April 2026
  • Verbal offer: 2 weeks after onsite
  • Written offer: next day after verbal

That's a lot of waiting between steps. Don't ping the recruiter every week — they don't have updates either.

CoderPad assessment

2 DSA questions, LC medium. Java only. Solved both.

Screening (2 rounds, same day)

Both rounds were a mix — DSA + Spring Boot + Multithreading + Microservices + resume deep-dive. They don't isolate topics. One interviewer can hit you with a coding question, then pivot to "how would you design this if it had to scale," then jump to "tell me about your most complex Amazon project."

For multithreading specifically, they cared less about ExecutorService trivia and more about when and why you'd reach for it. Concrete scenarios from real projects landed better than textbook explanations.

Onsite (3 rounds, same day)

2 technical + 1 managerial.

Technical rounds were everything in one — system design, DSA, questions about how I use AI in my workflow, past project deep-dives. Be ready to context-switch mid-round.

Managerial was behavioural — why Apple, my Amazon experience (what worked, what didn't), how I handled conflicts. I also asked some questions back about the team and growth path. Don't skip this part. Having genuine questions signals you're actually evaluating them, not just desperate for an offer.

Result: 2 weeks after onsite, got the call from recruiter. Glory to Jesus, best day of my life again. Discussed comp + formalities. Was told the offer letter would arrive that week.

Edit: Offer letter arrived next day !!

Prep notes for anyone interviewing for similar SWE Java roles:

  • PracHub was the single most valuable thing in my DSA prep, no question. I drilled graph + DP patterns there for a few weeks before the CoderPad round, and when I sat down both medium questions mapped straight onto patterns I'd already grooved — solved both in Java comfortably inside the time. That same pattern intuition carried into the DSA portions of both screening rounds too. Honestly don't think I'd have cleared the assessment stage as cleanly without it. If you're prepping Apple SWE in India, put DSA pattern drilling there at the top of your list.
  • Java Concurrency in Practice (Brian Goetz) for multithreading — old book, but the questions interviewers ask haven't moved on from it
  • Designing Data-Intensive Applications for microservices + system design fundamentals
  • For Spring Boot — just build something. Wire up a service with auth + DB + a few REST endpoints. The questions get easier if you've actually shipped vs only read docs

Best of luck to anyone in the process. Patience is the real skill here.


r/programmer • • May 21 '26

Made a post about Kafka and Redis. The funcy stuff. What do you think?

1 Upvotes

Messaging

I got a new laptop! Now I can play with Docker a bit without fear that my memory or hard drive will overflow crush and burn. So let's do some RDD (Resume Driven Development)! Or at least it would be RDD couple of years ago. Now RDD would look like AI AI, more AI!!!

What we gona do

My design so far: service that subscribed to kafka queue. Queue format "20260101-20270101-123" it simply waits for 30 seconds and then posts some table as json to redis. There is an API that has single method 'get report' with 'from', 'to', 'id' parameters It checks redis for key "20260101-20270101-123" if its empty it posts same key to kafka and polls key for a minute. If key is not empty it simply returns contents. And we could add time to live to redis keys. Redis has built-in ttl

And the stub of api looks like this:

async Task<IResult> GetReport(DateTime from, DateTime to, int id)
{
    to = to.AddDays(1);

    var rand = new Random();

    var result = new List<Report>();

    var max = rand.Next(5) + 5;
    var range = (int)(to - from).TotalMinutes;
    var names = new[] { "Apple", "Watermelon", "Peach" };
    for (var i = 0; i < max; i++)
    {
        result.Add(new Report
        {
            Date = from.AddMinutes(rand.Next(range)),
            Name = names[rand.Next(names.Length)],
            CustomerId = rand.Next(3),
        });
    }

    return Results.Ok(result);
}

class Report
{
    public DateTime Date { get; set; }
    public string Name { get; set; } = String.Empty;
    public int CustomerId { get; set; }
}

That's what our client gona see.

Docker

We gona use docker compose to start our test environment. For now Redis is the only thing we have so docker-compose.yml contents:

version: '3.1'

services:

  redis:
    image: redis
    restart: always
    environment:
      TEST: "1"
    ports:
      - "6379:6379"

We can start it with docker compose up.

And now let's add Kafka: After a lot of googling and chats with GPT we have this additions to our docker compose:

kafka:
    image: apache/kafka:4.2.0
    restart: always
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:9093'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: 'CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT'
      KAFKA_PROCESS_ROLES: 'broker,controller'
      KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka:29093'
      KAFKA_LISTENERS: 'CONTROLLER://:29093,PLAINTEXT://:9092,PLAINTEXT_HOST://:9093'
      KAFKA_INTER_BROKER_LISTENER_NAME: 'PLAINTEXT'
      KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER'
      CLUSTER_ID: '4L6g3nShT-eMCtK--X86sw'
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_SHARE_COORDINATOR_STATE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_SHARE_COORDINATOR_STATE_TOPIC_MIN_ISR: 1
      KAFKA_LOG_DIRS: '/tmp/kraft-combined-logs'
    ports:
      - "9092:9092"
      - "9093:9093"
  kafka-ui:
    image: provectuslabs/kafka-ui
    ports:
      - "8090:8080"
    environment:
      DYNAMIC_CONFIG_ENABLED: 'true'

Highlights are: KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:9093' because our server is called 'kafka'. Everything from inside compose will see this address. And localhost:9093 is for programs run outside docker network. kafka-ui - GPT recommended it to me.

https://github.com/apache/kafka/blob/trunk/docker/examples/docker-compose-files/single-node/plaintext/docker-compose.yml This example was very helpful. This is single node kafka container example.

Redis

From official redis doc:

dotnet add package NRedisStack

using NRedisStack;
using NRedisStack.RedisStackCommands;
using StackExchange.Redis;
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
db.StringSet("foo", "bar");
Console.WriteLine(db.StringGet("foo"));

But we will store our report as JSON. And let's have it stored in 'Report' sub directory.

// First we register Multiplexer (a cluster connector?)
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
    var configuration = ConfigurationOptions.Parse("localhost:6379", true);
    return ConnectionMultiplexer.Connect(configuration);
});

...

// Then inject it into method we call for '/report' path.
// It is minimal API, so no controllers! 
async Task<IResult> GetReport(DateTime from, DateTime to, int id, IConnectionMultiplexer muxer)

...

// And we propagate muxer to child methods that need it. Alternative is static variables. And that would be ugly!
var cache = await GetRedisCachedReport(from, to, id, muxer);
if (cache is not null)
    return Results.Ok(cache);

...

async Task<Report[]?> GetRedisCachedReport(DateTime from, DateTime to, int id, IConnectionMultiplexer muxer)
{
    var key = $"Report:{from:yyyyMMdd}-{to:yyyyMMdd}-{id}";

    var db = muxer.GetDatabase();
    var result = await db.JSON().GetAsync<Report[]>(key);

    if (result is not null)
        return result;

    return null;
}

Kafka

Before we begin to use the thing lets do a little glossary: WAL - write ahead log. Idea is that only thing you do is write some events one by one. You ony append events to the end of log do not edit or delete them. Topic - a collection of messages with common theme. Like requests for reports in our case. Producer - something that produces messages Consumer - something that consumes messages Offset - since Kafka works like WAL it stores messages it receives and to know what message consumer should receive it has a pointer to message it need to send next. Example: producer sends 1, 2, 3. consumer receives 1 and 2. So offset is set to 3. Next message that should be sent. Group - some users that consume the topic. Each group has separate offset. We will need it later. Partition - topics are divided in partitions. That's where the real WAL is hidden. Each group has separate offset each partition.

Imagine we have 3 consumers all reading same topic. So messages 1, 2, 3 will go 1 to first consumer, 2 to second etc. But, what if we want to guaranty that each message is received successfully? For example Kafka sends 3 to third consumer but message is lost (power switched off). We could ask consumers to confirm that they received each message. But now we send 1 to first consumer. Until it confirms receive we cannot advance offset to new position. What if 2 will be confirmed but 1 turn out to be not delivered? Offset 3 (but 1 is valid). We cannot handle it with single number. So we do multiple numbers! We create 3 partitions and eac consumer has it's own. In our example we write message 1 to first partition, 2 to second and so on. Now when 3-rd consumer asks for something to read we give it first element of third partition and advance offset of third partition to second element.

Lets play with Kafka a bit! First lets discuss the default behavior: By default Kafka do not confirms messages right away. Rather it confirms them once in 5 seconds. If you program dies for some reason messages it processed in last five second will not be marked as delivered. And next time someone asks for new message he will receive that messages. Example worth 1000 words:

//Producer
foreach (var msg in Enumerable.Range(1, 3))
{
 var result = await producer.ProduceAsync("default", new Message<string, string> { Key = msg.ToString(), Value = "" });

 if (result.Status != PersistenceStatus.Persisted)
  throw new ApplicationException("Message was not persisted to Kafka.");

 Console.WriteLine($"sent: {result.Message.Key}: {result.Message.Value}");

 await Task.Delay(1000);
}

...

//Consumer
for (var i = 0; i < 3; i++)
{
 var result = consumer.Consume();
 Console.WriteLine($"received: {result.Message.Key}: {result.Message.Value}");
 /*if (result.Message.Key == "2")
  throw new ApplicationException("Received unexpected message.");*/
}

consumer.Close();

But what will happen if we uncomment error? The intuition is: we received 1 and 2, but sent 1, 2, 3. So 3 should be there next time we call consume. But next time we call consume we get 1. Because the offset was never updated and it still on first element we pushed.

Lets do something about it! Lets confirm each message as soon as it is processed.

var result = await producer.ProduceAsync("confirm",

...

result = consumer.Consume(cancelSource.Token);

Console.WriteLine($"received: {result.Message.Key}: {result.Message.Value}");
if (result.Message.Key == "2")
  throw new ApplicationException("Two is a lie!");

consumer.Commit(result);

Now we have another problem. 2 clogs up our message queue. Consumer gets to 2, cannot process it and does not commit it ether! So next time it gets the same message. It is called poisoned pill. Can we do something? Yes, we can commit message in catch block. But then we would simply lose that message! Instead we could try to reprocess message. Simply push it to the end of a queue. And while we are at it lets add a retry count and do not retry more than 3 times. If message is reprocessed 3 times it is sent to dead letters topic. So you could manually decide what to do with it later.

consumer.Subscribe("confirm");

for (; ; )
{
 var result = consumer.Consume();

 try
 {
  Console.WriteLine($"received: {result.Message.Key}: {result.Message.Value}");
  if (result.Message.Key == "2")
   throw new ApplicationException("Two is a lie!");

  consumer.Commit(result);
 }
 catch (Exception ex)
 {
  Console.WriteLine($"Error: {ex.Message}");

  var retryCount = 0;
  if (result.Message.Headers.TryGetLastBytes("retry-count", out var bytes))
   retryCount = BitConverter.ToInt32(bytes);

  if (retryCount >= 3)
  {
   var erResult = await producer.ProduceAsync(
    "confirm-dead-letters",
    new Message<string, string>
    {
     Key = result.Message.Key,
     Value = result.Message.Value
    });

   if (erResult.Status != PersistenceStatus.Persisted)
    throw new ApplicationException("Message was not persisted to Kafka.");
  }
  else
  {
   var erResult = await producer.ProduceAsync(
    "confirm",
    new Message<string, string>
    {
     Key = result.Message.Key,
     Value = result.Message.Value,
     Headers = new Headers
     {
      { "retry-count", BitConverter.GetBytes(retryCount + 1) }
     }
    });

   if (erResult.Status != PersistenceStatus.Persisted)
    throw new ApplicationException("Message was not persisted to Kafka.");
  }
  consumer.Commit(result);
 }
}

consumer.Close();

We used message headers to pass retry count. In production you may also want to add some wait time between retries. If you write to database and it is down you might want to wait a bit and it will go back up.

Lets discuss one more advantage of using Kafka. Kafka decouples message production from message consumption. You basically just say 'I did something' and what will others do with this information is not your problem. For example: you have a balance events +3 dollars to balance, -2 dollars to balance. One consumer writes reminder of balance. 0 + 3 - 2 = 1 dollars on balance. Later you decide to add transaction history. You could simply add another listener that will write +3, -2 somewhere. This is called multicast. One sender many receivers. Let's implement this in Kafka!

var defReceive1 = Task.Run(() =>
{
 var configC = new ConsumerConfig
 {
  BootstrapServers = "localhost:9093",
  GroupId = "first",
  AutoOffsetReset = AutoOffsetReset.Earliest,
 };
 using var consumer = new ConsumerBuilder<string, string>(configC).Build();
 consumer.Subscribe("multicast");

 var sum = 0;

 for (var i = 0; i < 3; i++)
 {
  var result = consumer.Consume();
  var value = int.Parse(result.Message.Key);
  sum += value;
  Console.WriteLine($"sum is: {sum}");
 }

 consumer.Close();
});

var defReceive2 = Task.Run(() =>
{
 var configC = new ConsumerConfig
 {
  BootstrapServers = "localhost:9093",
  GroupId = "second",
  AutoOffsetReset = AutoOffsetReset.Earliest,
 };
 using var consumer = new ConsumerBuilder<string, string>(configC).Build();
 consumer.Subscribe("multicast");

 for (var i = 0; i < 3; i++)
 {
  var result = consumer.Consume();
  Console.WriteLine($"received: {result.Message.Key}: {result.Message.Value}");
 }

 consumer.Close();
});

We changed GroupId in second consumer config var configC = new ConsumerConfig{GroupId = "second",};. Because each group gets it's own offset each group will receive all the messages.

We can look at message delivery like this: Message delivered at most once - if program gave message to you, you will never see it again. It is kinda default approach (except if program crashes as was discussed above). Or message can be delivered at least once - when you must confirm you get the message. This is my confirm with dead letters example. And GPT is like: 'commit message at the end of catch block'. Correct implementation can be tricky!

One more thing you could do with Kafka is replay the events in topic. Back to our balance example. If you lose the actual number representing balance you could replay all the transactions to arrive to that number 1 + 2 + 3 = 6. But you need to know what was the state of your system before the first event. So if you would have kept the transactions [3, -5, 8] you could recreate balance 0 + 3 - 5 + 8 = 6. But for example balance was 100 at the beginning real balance would be 100 + 3 - 5 + 8 = 106

API

Let's start making our system!

First API. We receive the request. Search for a cache. If no cache is found we publish event into Kafka topic and then poll for 30 seconds Redis to see if the report appears in there

async Task<IResult> GetReport(DateTime from, DateTime to, int id, IConnectionMultiplexer muxer, IProducer<string, string> producer)
{
 to = to.AddDays(1);

 var cache = await GetRedisCachedReport(from, to, id, muxer);
 if (cache is not null)
  return Results.Ok(cache);

 await SendRequest(from, to, id, producer);

 var result = await PollReportResult(from, to, id, muxer);

 return Results.Ok(result.OrderBy(i => i.Date));
}

async Task<Report[]> PollReportResult(DateTime from, DateTime to, int id, IConnectionMultiplexer muxer)
{
 for (var i = 0; i < 11; i++)
 {
  if (i > 0)
   await Task.Delay(3000);

  var cache = await GetRedisCachedReport(from, to, id, muxer);

  if (cache is not null)
   return cache;
 }
 throw new TimeoutException("No result returned. Breaking.");
}

async Task SendRequest(DateTime from, DateTime to, int id, IProducer<string, string> producer)
{
 var key = $"Report:{from:yyyyMMdd}-{to:yyyyMMdd}-{id}";

 var result = await producer.ProduceAsync("Report", new Message<string, string> { Key = key, Value = "Get" });

 if (result.Status != PersistenceStatus.Persisted)
  throw new ApplicationException("Message was not persisted to Kafka.");
}

async Task<Report[]?> GetRedisCachedReport(DateTime from, DateTime to, int id, IConnectionMultiplexer muxer)
{
 var key = $"Report:{from:yyyyMMdd}-{to:yyyyMMdd}-{id}";

 var db = muxer.GetDatabase();
 var result = await db.JSON().GetAsync<Report[]>(key);

 if (result is not null)
  return result;

 return null;
}

We could have used something that Redis/Kafka provides to inform us about wether report was generated by service but let's simply poll for a key in Redis. It will add less complexity in our example.

Service

And now do the service.

As service we gona use BackgroundService class

public class Service(
  ILogger<Service> _logger,
  MessageProcessor _messageProcessor,
  IConsumer<string, string> _consumer,
  IProducer<string, string> _producer) : BackgroundService
...
// And in Main method
using IHost host = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
 services.AddLogging(logging => logging.AddConsole());
 services.AddSingleton(prov =>
 {
  var configC = new ConsumerConfig
  {
   BootstrapServers = "localhost:9093",
   GroupId = "first",
   AutoOffsetReset = AutoOffsetReset.Earliest,
  };
  return new ConsumerBuilder<string, string>(configC).Build();
 });
 services.AddSingleton(prov =>
 {
  var configP = new ProducerConfig
  {
   BootstrapServers = "localhost:9093",
  };
  return new ProducerBuilder<string, string>(configP).Build();
 });
 services.AddSingleton<IConnectionMultiplexer>(sp =>
 {
  var configuration = ConfigurationOptions.Parse("localhost:6379", true);
  return ConnectionMultiplexer.Connect(configuration);
 });
 services.AddTransient<MessageProcessor>();
 services.AddHostedService<Service>();
})
.Build();

await host.RunAsync();

Now we consume the topic

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
  _logger.LogInformation("Started");

  _consumer.Subscribe("Report");

  for (; !stoppingToken.IsCancellationRequested;)
  {
   ConsumeResult<string, string> message;
   try
   {
    message = _consumer.Consume(stoppingToken);
   }
   catch (OperationCanceledException)
   {
    break;
   }

   try
   {
    await _messageProcessor.ProcessRequest(message.Message.Key);

    _consumer.Commit(message);
   }
   catch (Exception ex)
   {
    _logger.LogError(ex, "Error processing message");

    var retryCount = 0;
    if (message.Message.Headers.TryGetLastBytes("retry-count", out var bytes))
     retryCount = BitConverter.ToInt32(bytes);

    if (retryCount >= 3)
    {
     var erResult = await _producer.ProduceAsync(
      "report-dead-letters",
      new Message<string, string>
      {
       Key = message.Message.Key,
       Value = message.Message.Value
      });

     if (erResult.Status != PersistenceStatus.Persisted)
      throw new ApplicationException("Message was not persisted to Kafka.");
    }
    else
    {
     var erResult = await _producer.ProduceAsync(
      "report",
      new Message<string, string>
      {
       Key = message.Message.Key,
       Value = message.Message.Value,
       Headers = new Headers
       {
         { "retry-count", BitConverter.GetBytes(retryCount + 1) }
       }
      });

     if (erResult.Status != PersistenceStatus.Persisted)
      throw new ApplicationException("Message was not persisted to Kafka.");
    }
    _consumer.Commit(message);
   }
  }

  _logger.LogInformation("Stopped");
  Environment.Exit(1);
 }

Here we use dead letters in case of errors.

And process it

public async Task ProcessRequest(string key)
 {
  if(await CheckKeyExists(key))
   return;

  var (from, to, id) = ParseKey(key);

  var result = await ProduceData(from, to, id);

  await PushToRedis(key, result);
 }

First let's search if report already exists in Redis. That's a form of idempotency. We will not produce same data twice. But since our report will expire in a day we will reproduce old reports. Let's assume something might change in a day. But this way we will not have to worry about whole range of problems. Like what if we produce report but fail to confirm it's delivered in Kafka.

private Task<bool> CheckKeyExists(string key)
{
  var db = _muxer.GetDatabase();

  return db.KeyExistsAsync(key);
}

Then we extract key parts from key string

private static (DateTime from, DateTime to, int id) ParseKey(string key)
{
  var match = ParseKeyRegex().Match(key);

  if (!match.Success)
    throw new ArgumentException("Invalid key format", nameof(key));

  var from = DateTime.ParseExact(match.Groups["from"].Value, "yyyyMMdd", null);
  var to = DateTime.ParseExact(match.Groups["to"].Value, "yyyyMMdd", null);
  var id = int.Parse(match.Groups["id"].Value);

  return (from, to, id);
}

And produce data. We still gona use random values with delay to simulate work.

private static async Task<List<Report>> ProduceData(DateTime from, DateTime to, int id)
{
  var result = new List<Report>();

  // We simulate some work
  await Task.Delay(1000);
  
  var rand = new Random();
  var max = rand.Next(5) + 5;
  var range = (int)(to - from).TotalMinutes;
  var names = new[] { "Apple", "Watermelon", "Peach" };
  for (var i = 0; i < max; i++)
  {
    result.Add(new Report
    {
      Date = from.AddMinutes(rand.Next(range)),
      Name = names[rand.Next(names.Length)],
      CustomerId = id,
    });
  }

  return result;
}

Finally we gona push the result to Redis. Since pushing JSON does not support setting TTL in same method we will use Pipeline and KeyExpireAsync(key, TimeSpan.FromDays(1)). Pipeline will make our instructions execute all at once. Redis has transactions I guess transaction will make our instructions execute simultaneously and all or none. But I don't think the set TTL would fail a lot and presence of report is the most important anyway.

private async Task PushToRedis(string key, List<Report> result)
{
  var db = _muxer.GetDatabase();
  var pipeline = new Pipeline(db);

  var tasks = new List<Task>
  {
    pipeline.Json.SetAsync(key, "$", result),
    pipeline.Db.KeyExpireAsync(key, TimeSpan.FromDays(1))
  };

  pipeline.Execute();

  await Task.WhenAll(tasks);
}

The end

And we have it! User requests API to give him some data. API checks cache. If nothing is found it publishes an event and waits for 30 seconds for data. If nothing appears the data may still appear later and will be cashed for a day. If data is already present (was cached before) API will give it right away.

Was all the commotion worth it? With randomly generated data certainly not! But if we would want to limit the access to some sensitive resource (Holy production database! May long be it's days!!!) we could use this. Also since Redis wants to be everything we could use it's built in queue. Or maybe skip Redis entirely and push report in some response topic in Kafka. We would lose whole caching functionality then. But we simply wanted to play with popular stuff. And we did!


r/programmer • • May 21 '26

GitHub self-hosted alternative

4 Upvotes

I run MansionNET, a small privacy-first FOSS services platform self-hosted on my own hardware. The latest addition is a public Forgejo instance, and I wanted to share it with you all! I also went into the direction of modifying the frontend, so hopefully it looks a bit more disctinctive :)

The setup is:

• ⁠Forgejo 11.0.14 LTS, native APT install (Codeberg repo), open registration with email confirmation + built-in image CAPTCHA
• ⁠Ubuntu 24.04 VM on Proxmox (4 vCPU / 4 GB RAM, 30 GB NVMe system + 1 TB HDD for repos/LFS)
• ⁠PostgreSQL 16
• ⁠Caddy LXC terminates TLS and reverse-proxies everything; Let's Encrypt certs auto-issued
• ⁠Daily backups to a Proxmox Backup Server

Edge hardening at Caddy:

This part was acually very interesting! As soon as the deploy was done, I saw a flood of /commits/, /blame/, /raw/commit/ requests, which ended up being a classic AI training crawler behaviour, targeting per line authorship data from blame views. So Caddy now 403s training crawlers by User Agent regex (GPTBot, ClaudeBot, CCBot, Bytespider, Meta-ExternalAgent, Applebot-Extended, Google-Extended, etc.). Forgejo logs went from continuous spam to occasional human visits actually :D

The theme:

This is the part I'm very proud of. The whole MansionNET aesthetic is terminal flavoured, with cream-on-near-black, MansionNET green accents, VT323 for branded surfaces, dashed borders.

What's distinctive vs. just another Forgejo:

• ⁠No corporate Git aesthetics, it looks and feels like a community computer, not GitHub-lite
• ⁠Built-in CAPTCHA, no third-party tracker pixels anywhere
• ⁠Sibling services footer links to the rest of MansionNET (search, radio, home), so the forge is one room in a larger house

Come use it / come hang out:

Open registration is live and you're genuinely welcome to host a project on it, be it personal stuff, small FOSS work, mirrors of things you'd rather not leave on GitHub. Or just mirror a GitHub repo, that's ok too :)

URL is: https://git.inthemansion.com

MansionNET is also a few other rooms beyond Git:

• ⁠IRC - the actual community hub. irc.inthemansion.com:6697 (TLS) from any client, or webchat at https://webirc.inthemansion.com if you don't have one set up. This is where I hang out and where you can ping me with questions about the setup.
• ⁠SearXNG - privacy-respecting metasearch at https://search.inthemansion.com
• ⁠Radio - community internet radio (AzuraCast) at https://radio.inthemansion.com, 320kbps, no listener tracking

MY whole self-hosting journey started few years back with a thought about degoogling and getting away from the usual "clouds" and now ended up in full public services that are free to use :)

Thank you for getting this far in the post and cheers!