C Plus Plus

7 posts

google3 min readCurated summary

Optimizing cloud economics with linear elastic caching

Linear elastic caching treats cache memory as a variable cost rather than a fixed allocation. It dynamically adjusts how long pages remain in memory by balancing ongoing memory expense against the cost of fetching evicted data again, using the ski rental problem as its theoretical foundation. Experiments in Spanner and public cache traces show meaningful cost reductions with only modest increases in misses. ## Fixed-Size Cache Limitations - Traditional caches allocate a fixed amount of RAM and use policies such as LRU when space runs out. - Undersizing the cache causes excessive disk or storage access and poor performance. - Oversizing it wastes money during periods of low demand; some serverless providers charge up to $3 per day for 1 GiB of memory. - Fixed sizing therefore creates a “Goldilocks” problem as workloads fluctuate. ## Ski Rental Model for Cache Eviction - Each cached page presents two choices: - **Rent:** Keep it in RAM and continuously pay for its memory footprint. - **Buy the miss:** Evict it and risk a latency and I/O penalty if it is requested again. - A ski rental algorithm assigns each page a time-to-live (TTL). - If the page is not accessed before its TTL expires, it is evicted. - If the cache becomes physically full, a conventional policy such as LRU handles capacity pressure. - The researchers prove that eviction policy and rental duration can be optimized separately, simplifying implementation. - Unlike worst-case break-even or randomized ski rental strategies, lightweight machine learning can exploit predictable workload patterns. ## Lightweight TTL Prediction - In Spanner, each page receives a TTL based on: - Page size - Cost of a cache miss - Type of database operation - Observed access behavior - A shallow decision tree was chosen because Spanner processes billions of requests per second. - The model can be translated into a few lines of interpretable C++ code. - Its cost-aware decisions allow extra misses mainly for data that is inexpensive to retrieve. ## Spanner Production Results - Compared with a standard fixed-size cache: - Memory usage fell by **15.5%**. - Cache misses increased by only **5.5%**. - Total cost of ownership fell by approximately **5%**. - The additional misses increased actual I/O costs by only **0.5%**, because they were concentrated on cheap-to-fetch data. - The policy was deployed on production Spanner servers and evaluated over several months. ## Public Trace Evaluation - The approach was tested on public industry cache traces using GDSF as the fixed-size baseline. - GDSF generalizes LRU to account for pages with different sizes. - Researchers evaluated four elastic-cache variants using: - Break-even or randomized ski rental policies - Learned or non-learned TTL selection - Because public traces lacked application-level features, learning used the first half of each trace to calculate the best TTL for individual pages. - Caches were warmed with one day of requests before performance measurement began. ## Overall Results - Elastic caching consistently produced lower total cost across diverse workloads. - Its advantage increased as memory became more expensive relative to cache misses. - At comparable cache sizes, elastic policies also achieved substantially lower miss rates than fixed-size approaches. Linear elastic caching is most useful when memory costs vary significantly or workloads are bursty and predictable. Dynamically assigning page TTLs offers a practical way to reduce memory spending while limiting performance impact, especially when the system can estimate the cost of each miss.

Read original(opens in new tab)
gitlab3 min readCurated summary

Claude Code and GitLab: Three workflows that ship

Claude Code accelerates coding, but writing code is only one part of shipping software. The post argues that GitLab complements Claude Code by handling CI/CD, security scanning, code review, approvals, and auditability. It presents three workflows: fixing bugs locally, enriching Claude with GitLab context through MCP, and using a Claude-powered external agent to resolve merge request feedback. ## The Gap Between Coding and Shipping - Agentic tools can quickly understand unfamiliar code, propose fixes, and scaffold features. - Faster code generation can leave teams with: - Larger bug backlogs - More pipeline failures - Accumulating security vulnerabilities - Bottlenecks in review and approval - GitLab manages the downstream software lifecycle after Claude Code produces a change. ## Prerequisites and Project Setup - Claude Code must be installed and configured. - A GitLab project containing bug reports and feature proposals is required, such as the Tanuki IoT Platform. - Optional workflows require: - The GitLab MCP Server - GitLab Duo Agent Platform with external agents - The example project uses CMake, Make, and GCC or Clang for C++ builds. - Developers clone the repository, launch `claude`, and can ask it to explain the project before making changes. ## Workflow One: Fix a C++ Bug and Ship It Through GitLab - The Arduino IoT Collector crashes when `/dev/ttyACM0` is unavailable. - The failure can be reproduced by building and running the application with CMake: - `cmake -S . -B build` - `cmake --build build` - `./build/arduino_iot_collector` - Claude Code examines `sensors/arduino-iot-collector/src/main.cpp` and identifies an uncaught `std::runtime_error`. - The recommended behavior is to log a clear configuration error and continue running instead of terminating. - After the fix, Claude Code can create a branch, commit the changes, and push them, or the developer can run the Git commands manually. - Opening a merge request triggers: - Build and test pipelines - Security scanning - GitLab Duo Code Review Flow - Checks against project style guides and custom review instructions ## Workflow Two: Add GitLab Context with MCP - Local repository files may not contain the full history behind a bug. - GitLab issues, debugging discussions, previous merge requests, and related fixes provide valuable software development lifecycle context. - The GitLab MCP Server connects Claude Code to this information. - It can be added over HTTP with a command such as: `claude mcp add --transport http GitLab https://gitlab.example.com/api/v4/mcp` - In a new Claude Code session, `/mcp` starts OAuth authentication through the browser. - Developers can verify the integration by asking Claude which GitLab MCP tools and server version are available. - MCP uses the developer’s existing GitLab identity: - It does not grant elevated permissions. - Claude can access only projects, issues, merge requests, and other data already visible to that user. ## Workflow Three: Resolve Review Feedback with an External Agent - The third workflow uses a Claude-powered external agent in GitLab Duo Agent Platform. - Rather than requiring a developer to manually interpret review comments, the agent can address code review feedback directly in the merge request. - This extends Claude Code’s implementation abilities into GitLab’s review and delivery workflow. ## Overall Recommendation Use Claude Code for investigation and implementation, then use GitLab to provide the context, automated validation, security checks, review, and approval process needed to ship those changes safely.

Read original(opens in new tab)
discord3 min readCurated summary

Announcing Discord’s Social SDK, Helping Power Your Game’s Social Experiences

Discord’s Social SDK brings Discord-powered social features directly into games, allowing players to connect whether or not they have Discord accounts. Available at no cost for C++, Unreal Engine, and Unity developers, it supports unified friends, invitations, rich presence, and account linking. Discord says the SDK is designed to improve discovery, retention, and multiplayer communication, with expanded messaging, channels, and voice features available through a closed beta. ## SDK Availability and Purpose - Released on March 17, 2025, during the Game Developers Conference. - Available for: - C++ games - Unreal Engine - Unity - Currently supports Windows 11 and macOS. - Console and mobile support is planned. - Designed to bring Discord’s social infrastructure to games while preserving a seamless player experience. ## Core Social Features - **Unified Friends List** - Players can view Discord friends in-game. - In-game friends can also be surfaced through Discord. - **Deeplink Game Invites** - Players can invite Discord friends directly into a specific party, lobby, or session. - This reduces friction for joining multiplayer games and may improve retention. - **Rich Presence** - Displays a player’s game activity in Discord. - Supports one-click joins from Discord profiles. - Available across PC, console, and mobile. - Helps games gain visibility and attract additional players. - **Flexible Account Requirements** - Players can use the integrated social experience without owning a Discord account. - Optional account linking connects their in-game and Discord identities. - Provisional accounts support players who do not sign up for Discord. ## Closed-Beta Communication Features Several features are available to developers with limited access and can be fully enabled through Discord’s closed beta: - **Cross-Platform Messaging** - Enables conversations between in-game players and Discord users. - Direct messages can persist across both environments. - Discord accounts are not required for every participant. - **Linked Channels** - Connects in-game chat to selected Discord server channels. - Supports persistent communication for guilds, squads, and other groups. - **Discord Voice Chat** - Brings Discord’s voice technology directly into games. - Intended for guilds, matches, and in-game lobbies. ## Early Developer Integrations Discord tested and refined the SDK with developers including Facepunch Studios and Theorycraft Games. - Facepunch Studios reported that the Unity sample made integration straightforward and provided reusable examples for adapting the SDK to *Rust*. - Discord used partner feedback to improve: - Online visibility controls - Provisional-account behavior - Consistency for players without Discord accounts - Theorycraft Games highlighted direct messaging, lobbies, session invites, and provisional accounts as valuable features in *SUPERVIVE*. Game developers can begin using the freely available Social SDK today, while teams seeking cross-platform messaging, linked channels, and integrated voice should apply for the closed beta.

Read original(opens in new tab)
figma3 min readCurated summary

Figma’s journey to TypeScript | Figma Blog

Figma migrated its custom Skew programming language to TypeScript after its original performance advantages became less important than its maintenance and onboarding costs. Advances in mobile WebAssembly support, C++ engine integration, and team growth made the transition practical without sacrificing significant performance. The team completed the migration through an automated, gradual rollout that preserved development velocity and minimized production risk. ## Why Figma Moved Away from Skew - Skew originally helped Figma support prototype viewing across web and mobile. - Its compiler provided optimizations such as: - Constant folding - Devirtualization - Efficient JavaScript integer operations - Fast compile times - Over time, Skew became difficult to scale because: - New engineers struggled to learn it. - It integrated poorly with the broader codebase. - It lacked an external developer ecosystem. - Maintaining its specialized tooling outweighed its performance benefits. - TypeScript offered native package management, static imports, modern language features, extensive tooling, and easier hiring and onboarding. ## Why the Migration Became Possible - Mobile browsers gained broad WebAssembly support by 2018, with reliable performance by 2020. - Figma moved many performance-critical Skew components—especially hot paths such as file loading—to its C++ engine. - These C++ replacements reduced the performance penalty of moving less-critical code to TypeScript. - Larger prototyping and mobile teams provided enough capacity to invest in automated migration tooling. ## Addressing Performance Concerns - In 2020, early benchmarks showed TypeScript could make prototype loading nearly twice as slow in Safari. - Safari was especially important because WebKit was the only browser engine permitted on iOS at the time. - Improved WebAssembly support and the shift of core engine work to C++ made Skew’s compiler optimizations less essential. - Figma gained confidence that TypeScript could provide acceptable performance without recreating Skew’s custom compiler. ## Automated Skew-to-TypeScript Conversion - Manually rewriting the entire codebase would have disrupted development and increased the risk of runtime bugs and regressions. - Figma built a transpiler that converted Skew into TypeScript, extending earlier work by former CTO Evan Wallace. - The migration required care because Skew and TypeScript had different runtime semantics. - For example, TypeScript initializes namespaces and classes only after a module is imported, while Skew made symbols available globally when the codebase loaded. Unexpected import order could therefore introduce runtime failures. ## Three-Phase Rollout ### Phase 1: Write Skew, Build Skew - Figma kept the existing build process. - The new transpiler generated TypeScript from Skew. - Generated TypeScript was checked into GitHub so developers could inspect and prepare for the future codebase. ### Phase 2: Write Skew, Build TypeScript - Once the generated bundle passed unit tests, production traffic began using the TypeScript build. - Developers continued writing Skew. - The transpiler updated the TypeScript source automatically. - The team fixed type errors incrementally; TypeScript could still produce valid bundles despite those errors. ### Phase 3: Write TypeScript, Build TypeScript - After the team adopted the TypeScript build, the generated code became the source of truth. - Figma stopped automatic generation, deleted the Skew source, and required new development to use TypeScript. - The staged process allowed the team to detect and resolve issues such as a Smart Animate regression before completing the cutover. ## Practical Lessons - A custom language can provide valuable early advantages but become a long-term developer-experience liability. - Automated conversion is safer when paired with staged production rollouts and reversible adoption gates. - Controlling the original compiler made it possible to adapt the migration tooling to the codebase’s specific needs. - Figma’s approach demonstrates that large language migrations can preserve delivery speed when technical, performance, and organizational prerequisites are addressed first.

Read original(opens in new tab)
figma3 min readCurated summary

Illuminating dark mode | Figma Blog

Dark mode looked like a simple color swap, but Figma found it required a broad redesign of its UI architecture and engineering processes. The project aimed not only to satisfy user demand and improve accessibility, but also to create a scalable foundation for future themes. Figma ultimately treated dark mode as a systems problem involving product scope, shared components, edge cases, and maintainability. ## Accessibility and User Demand - Dark mode became Figma’s most requested feature after users complained about bright screens during late-night work. - It could improve legibility for people with certain visual impairments and aligned with Figma’s mission of making design accessible. - The team also considered WCAG contrast requirements rather than treating the feature as purely cosmetic. - Figma shipped dark mode in May 2022 after months of product, design, and engineering work. ## The Complexities of Color - The initial idea was to replace light colors with dark ones, but this approach would not scale as the product evolved. - Figma wanted a solution that: - Made new features support dark mode by default. - Simplified onboarding for engineers. - Reduced regressions when experimenting with themes. - Could support additional themes in Figma and FigJam. - Some decisions were straightforward: - Light editor panels would become dark. - Text and icons would become light foreground elements. - Toolbars and menus already dark in light mode would remain dark. - Other questions required product decisions: - Which parts of Figma should support dark mode? - Should user-created canvas content, such as the canvas background, change with the theme? - Should colors rendered by the C++ editor engine, including the transparency grid, also change? ## Auditing the Product Surface - Before coding began, team members audited Figma’s UI to estimate the work required for each surface. - The project involved far more than the main editor: - Modals - Panels - Toolbars - Dropdowns and submodals - Hidden states and complex edge cases - Each surface needed its full range of views and states considered, not just its most commonly seen appearance. ## Building a Systematic Approach - At kickoff, ten product engineering teams owned major parts of Figma’s interface. - Shared UI components had to be refactored so they could support dark mode where appropriate while remaining unchanged on unsupported surfaces. - The team recognized that a small central engineering group could not manually handle every component and state. - This drove the need for a systematic, regression-resistant approach that could scale across teams and continue supporting future product development. Figma’s experience shows that theme support should be designed as an extensible system, not implemented as a one-time recoloring exercise. Teams planning similar work should begin with a full product audit, define theme boundaries clearly, and invest in shared components and automation that make future themes easier to add.

Read original(opens in new tab)
figma3 min readCurated summary

Figma is powered by WebAssembly | Figma Blog

WebAssembly reduced Figma’s load time by more than three times after replacing its asm.js-based C++ runtime. The improvement came primarily from faster parsing, native-code compilation, and caching—not from a major reduction in compressed download size. Figma’s experience demonstrated that WebAssembly could deliver substantially faster, desktop-quality web applications, though browser support and implementation differences remained limitations. ## What WebAssembly Changes - WebAssembly is a compact binary format for machine code designed specifically for browsers. - Figma’s C++ code was a strong candidate because C++ can be compiled directly to WebAssembly. - Before WebAssembly, Figma used asm.js, a restricted JavaScript subset that represents memory as a large numeric array. - WebAssembly preserves asm.js’s limitations: - It primarily loads and stores numbers. - It must call JavaScript for browser APIs such as the DOM and networking. - It remains subject to the browser sandbox. ## Why WebAssembly Is Faster Than asm.js - **Smaller and faster to parse:** WebAssembly’s binary format transfers efficiently and parses around 20 times faster than asm.js. - **Ahead-of-time optimization:** LLVM optimizes the C++ code before compilation, allowing browsers to translate it directly to native code. - **Effective caching:** Browsers can cache the translated native code, making subsequent loads nearly free. - **Native 64-bit integer support:** WebAssembly avoids the slower emulation required by JavaScript’s 53-bit integer limitation. - **Less runtime optimization work:** Unlike JavaScript, WebAssembly does not require extensive browser optimization passes for code that was already compiled and optimized. ## Figma’s Load-Time Results - Figma measured load time from application initialization through downloading and rendering an entire design for the first time. - Switching from asm.js to WebAssembly improved load time by more than three times across document sizes. - The gain was especially meaningful because Figma users often work with large documents and switch between them frequently. - Subsequent loads could benefit further from cached WebAssembly-to-native translations. - The compressed download size improved only slightly because compressed asm.js was already close in size to compressed WebAssembly. ## Browser Support Limitations - At the time of publication, WebAssembly was enabled by default in Firefox and Chrome. - Edge and Safari were still developing their implementations. - Figma enabled WebAssembly only in Firefox because Chrome’s implementation had blocking issues, including the lack of caching for translated WebAssembly code. - These browser-specific differences affected whether the performance benefits could be consistently delivered. Figma’s results suggested that teams with substantial C or C++ code should seriously consider WebAssembly for performance-sensitive web applications. The largest benefits were faster startup and reusable native-code caching, while download-size improvements were comparatively modest.

Read original(opens in new tab)
figma2 min readCurated summary

Debugging Data Corruption with Emscripten | Figma Blog

Figma encountered intermittent save-file corruption caused by an elusive C++ memory-safety bug. Conventional debugging tools failed because the web app’s asynchronous behavior made the problem nondeterministic. A keyboard-and-mouse fuzzer eventually produced reproducible failures, while understanding Emscripten’s C++-to-JavaScript memory model helped narrow the investigation. ## Detecting the Corruption - Invalid save files appeared occasionally and could not be reliably reproduced. - Figma’s files used ZIP containers around Google FlatBuffers documents. - The serialized bytes looked mostly valid, but some offsets were unexpectedly zeroed. - Data being written to the wrong location suggested a memory-safety violation such as: - Use before initialization - Use after free - Out-of-bounds access ## Why C++ Made the Bug Difficult - C++ was valuable for Figma because it provided: - Access to libraries such as FreeType, HarfBuzz, and Skia - Low-level control suitable for graphics software - Mature debugging and optimization tools - However, C++ offers no built-in protection against memory errors. - The team tried avoiding deallocation, enabling malloc diagnostics, fixing Valgrind and Clang Analyzer findings, and upgrading the compiler, but none exposed the corruption. ## Reproducing the Failure with Fuzzing - The team planned to eliminate nondeterminism by recording user events and replaying them deterministically. - Building a complete session recorder was too large a project, so they limited inputs to keyboard and mouse events. - A fuzzer generated random event sequences and ran them against the application. - After several days, it produced multiple save failures, providing reproducible cases for debugging. ## Emscripten’s Emulated Memory Model - Figma’s C++ editor ran in the browser through Emscripten, which compiled C++ into JavaScript. - JavaScript typed arrays and shared `ArrayBuffer` storage allowed Emscripten to emulate contiguous C++ memory. - In the generated code: - Pointer loads became typed-array reads. - Pointer stores became typed-array writes. - Registers became local variables. - Shared buffers enabled pointer reinterpretation between types. - Emscripten generated asm.js-style JavaScript, using type annotations and operations optimized for JavaScript JIT compilers. The combination of deterministic fuzzing and knowledge of Emscripten’s low-level memory representation provided the path toward isolating the corruption, even though the ultimate fix was reportedly only a three-line change.

Read original(opens in new tab)