Pinterest Engineering | Medium Note

Pinterest Engineering | Medium

Pinterest Engineering, showcased on Medium, provides a behind-the-scenes look at the technological innovations driving the popular visual discovery platform. Through in-depth articles, engineers share insights into their work on scalability, machine learning, data infrastructure, and more. The publication highlights Pinterest's engineering culture, emphasizing collaboration, experimentation, and a passion for solving complex problems. Readers can explore topics like building recommendation systems, optimizing search functionality, and developing tools for data analysis. The content offers valuable perspectives for engineers and tech enthusiasts interested in the intricacies of a large-scale platform like Pinterest. Whether delving into the challenges of image recognition or the evolution of their infrastructure, Pinterest Engineering on Medium provides a fascinating glimpse into the technical side of a beloved online destination.

Thread Of Notes

CdXz5zHNQW_HJwkDbk2Uz.png
Pinterest leverages Vision-Language Models (VLMs) to enhance its visual search and discovery platform. These models are crucial for powering new features like Pinterest Assistant and hybrid search. Pinterest customizes open-source VLMs to meet its specific product and scale requirements. Serving VLMs presents unique challenges beyond traditional text-only LLMs, including handling multiple images and larger KV caches. To address these, Pinterest built its VLM serving stack on NVIDIA Blackwell GPUs and NVIDIA Dynamo. Blackwell GPUs offer superior compute throughput and memory capacity for demanding AI workloads. Dynamo provides a distributed orchestration layer for optimizing multimodal inference across the entire serving path. Request payloads for VLMs are more complex, requiring image downloading, preprocessing, and prompt construction. The prefill stage in VLM serving is often dominant and computationally expensive, necessitating advanced cache management. Multi-turn VLM interactions further complicate serving due to evolving visual context and heavier prefill demands. Managing KV cache memory pressure is critical, requiring strategies like KV-aware routing and offloading. Pinterest's solution utilizes disaggregated prefilling and decoding, KV cache offloading with LMCache, and multimodal support within Dynamo and vLLM. They also implemented custom projection embeddings to reduce the cost of processing large visual contexts. This optimized VLM serving stack significantly improves performance, demonstrating substantial gains in Time-to-First-Token.
CdXz5zHNQW_ydHVPNTidy.png
The transformation into an AI team requires a fundamental shift in operational models, philosophies, and roles, moving beyond simply using AI tools. Team members become empowered strategists and problem-solvers, leveraging AI for automation and analysis to focus on higher-level thinking. This evolution makes previously intractable problems solvable and drastically alters the nature of engineering work. Pinterest's infrastructure teams are adapting this out of necessity to scale reliability and efficiency. Accessible AI tools significantly raise performance ceilings, enabling complex projects like codebase refactoring to be completed in days instead of months. This expanded capability necessitates even more critical strategic prioritization, as feasibility doesn't equate to strategic alignment. Engineers will shift from execution to strategic thinking, problem definition, and validating user needs, using AI as a force multiplier. Managers will move from process enforcement to strategic guidance, focusing on vision, maximizing impact, and talent development. Pinterest is actively implementing AI for data exploration, content creation, and infrastructure improvements. The future of high-performing teams is intrinsically linked to the symbiotic relationship between human expertise and machine intelligence. Teams must embrace this cultural change to remain competitive and innovative. AI integration increases team capacity, creating a surplus needed for skill development and fuller tool leverage. The transition to an AI-powered environment is complex and turbulent, requiring leadership to navigate the deluge of information and guide teams effectively.
CdXz5zHNQW_hKF1eaOw11.png
Pinterest's home feed aims to retrieve relevant Pins for users by improving its recommendation system. Initially, a two-tower model was used, encoding users and items separately, but this struggled with users' multiple interests. Conditional Learned Retrieval (CLR) was developed to address this by conditioning user embeddings on explicit retrieval contexts. Prior work explored bootstrapping CLR for notifications and integrating it into a multi-embedding framework for the home feed. This blog details CLR's evolution into a broader retrieval system for the Pinterest home feed.CLR was expanded to support diverse retrieval candidates by incorporating new condition types like Interests, Pins, and Boards. Interest conditions were initially bootstrapped from user signals and later enhanced with LLM-generated interests. Pin conditions involved clustering engaged Pins and representing them with embeddings, allowing CLR to replace legacy generators. Board conditions were created by using random walks on the Pin-Board graph and representing Boards with embeddings.The model foundations were scaled using sequence modeling and improved condition representations. A Conditioned User Sequence Transformer was introduced to make CLR sequence-aware by encoding user actions alongside condition tokens. This evolved into a Foundation Model-based CLR architecture, integrating a large-scale transformer trained on global user sequences. This foundation model uses shared Pin embeddings for both user and item towers and incorporates a contrastive alignment loss.Condition representation was unified to handle heterogeneous conditions within a single model, reducing duplicated work. Unified CLR consolidated different condition types into one model, accepting multiple conditions and imputing missing features. Router simplification involved refactoring routing logic into a condition-agnostic Slot Architecture with predefined slots for different embedding types.Training efficiency for CLR was enhanced through lossless infrastructure optimizations that doubled training throughput. Request-level training deduplicates identical user features within a batch, and further optimizations are ongoing. The system now efficiently handles multi-condition retrieval at production scale, improving user engagement through more diverse and relevant content.
CdXz5zHNQW_6wtn6E8XMD.png
Pinterest aims to help users discover inspiration for a better life through its recommendation system. The home feed, a key discovery platform, utilizes a multi-stage pipeline for recommendations. Previously, optimization focused on engagement metrics like clicks and saves. However, engagement and retention are distinct, and optimizing solely for engagement can lead to user churn.This post introduces Pinner Progression, a program that prioritizes user retention by understanding their evolving needs. The core idea is to combine sequential user understanding with persistent use-case representation. This approach helps anticipate user actions and offer recommendations that foster serendipitous discovery. A key signal introduced is User Interest Clusters (UICs), which represent distinct use-cases users engage with.Sustainable growth relies on building lasting user relationships with specific use-cases, not just short-term engagement. Analysis shows that the adoption of use-cases correlates with sustained engagement and retention. Modern recommendation systems excel at understanding current user preferences but struggle to model the lifecycle of these preferences. Distinguishing between a user's active "apartment decorating" phase and a decaying "sourdough" phase is crucial for long-term retention.UIC representation builds upon past work like PinnerSage and OmniSage. It innovates by personalizing clustering to engaged content only, allowing a dynamic number of clusters per user. Crucially, each UIC includes stateful lifecycle metadata, providing temporal and behavioral insights. This metadata helps infer the maturity of a user's interest, differentiating fleeting curiosity from emerging habits.UICs are defined by medoids and landmark Pins within the OmniSage embedding space, where closeness signifies functional utility. Signal construction involves hierarchical clustering of a user's recent engagement embeddings. The complete linkage algorithm merges clusters based on the similarity of their least similar pairs, with a similarity threshold. This process stops when no remaining pair exceeds the threshold or a maximum cluster count is reached.System-level integration involves using UICs as a shared abstraction across the retrieval, ranking, and blending stages of the recommendation pipeline. This allows different system components to reason about the maturity of a user's interests. UICs are externalized to a shared feature store for efficiency, reducing latency associated with multiple signal fetches. Future work includes extending UICs with long-sequence representations that preserve temporal dynamics. Retrieval is the first integration point, where Conditional Learned Retrieval generates candidates using user information and conditions to ensure semantic relevance.
CdXz5zHNQW_3eUbsaOfmV.png
Managing Infrastructure as Code in a large, distributed organization like Pinterest presents significant security and logistical hurdles. To address this, Pinterest developed the Resource Provisioner Pipeline (RPP), a proprietary Terraform execution engine. RPP ensures secure management of both critical and non-critical infrastructure changes within a multi-repository setup. This system provides compliance and robust security for global AWS operations through dual controls, centralized GitHub Actions, and secure role-chaining. RPP manages hundreds of Terraform workspaces, governing tens of thousands of AWS resources including security policies, networking, and compute. The RPP GitHub workflow operates on a centralized execution model, triggered by PR events. It uses composite GitHub Actions and isolates workspace impact by executing plans for each workspace independently. Dual controls add an essential human review layer, requiring approval from a code reviewer. To enforce least privilege, RPP implements a strict workspace-path-role mapping using secure role-chaining. The process starts with assuming a centralized RPPActionsRole authenticated via GitHub OIDC. It then determines workspace properties, mapping them to allowed repositories, paths, and execution roles. A critical backend validation ensures code paths strictly reference the correct S3 state backend and KMS keys for the designated workspace. If validation passes, the RPPActionsRole assumes a down-scoped team IAM role, ensuring minimal permissions. The deployment process includes linting, planning with output on the PR, and deliberate application triggered by a specific comment. This approach offers benefits like unified auditing, instant systemic patches, and centralized resource metrics.
CdXz5zHNQW_ggFzV94AMK.png
CdXz5zHNQW_MsiwuAmomZ.png
Pinterest has developed a robust, automated schema evolution framework for their Kafka-based CDC ingestion platform. Schema changes are a critical, cross-system contract, and unchecked evolution can lead to pipeline failures and data inconsistencies. Their solution focuses on making schema evolution safe, repeatable, and scalable by treating it as a multi-stage convergence process. The architecture involves CDC sources, Kafka, Flink for transformation, and Spark for upserts into Iceberg tables.A core component is a reliable onboarding model that uses schema definition files with stable numeric identifiers as the source of truth. Updates propagate automatically across Kafka, Flink, Spark, and Iceberg through a PR-based rollout with versioning and auditing. The system supports primarily additive schema changes to maintain backward compatibility and minimize complexity. Type changes are strictly limited to those preserving semantic meaning, like numeric precision widening.Schema evolution is managed through a three-phase convergence model to maintain pipeline availability. Phase one updates Iceberg schemas, phase two deploys updated Flink and Spark code, and phase three ensures data convergence. This phased approach decouples schema propagation from data correctness, allowing temporary divergence within a defined SLA. Pinterest employs an SLA-based model for schema evolution, prioritizing predictability and operational safety.Deployment strategies are carefully managed, especially for Flink, to prevent data loss. Unsupported or ambiguous cases, such as default values or primary key changes, have specific manual recovery paths. Ambiguous CREATE TABLE diffs are resolved by comparing against the database's actual DDL history rather than inferring intent from textual changes. Concurrent schema changes are handled sequentially to prevent race conditions, ensuring serialized convergence. Column transformations are managed by annotating schemas with required transformations, which are then injected into the ingestion pipeline. Error handling and recovery mechanisms, particularly for Spark failures, ensure that processing resumes from the last successful watermark.
CdXz5zHNQW_srAU1TSiiq.png
CdXz5zHNQW_AFL9DXaCyE.png
CdXz5zHNQW_rmxcXIRNOK.png
Pinterest's online ML serving system uses a root-leaf architecture where client services request scores for Pins. The root component handles feature retrieval and preprocessing, while leaves perform model inference, often on GPUs. This design simplifies onboarding new models and optimizes resource utilization by separating CPU and GPU workloads. However, it led to a network bottleneck between the root and leaf partitions due to passing many features.Initially, lz4 compression was implemented to reduce network usage, resulting in significant bandwidth savings but with a slight increase in CPU usage and latency. This was a good start, but the core issue of shipping unnecessary features persisted. The "Send What You Use" approach was then developed to address this by only sending features that a specific model requires.The model signature, which defines a model's inputs and outputs, serves as the source of truth for feature requirements. As models are trained and exported, their signatures are saved alongside them. Leaften load these signatures to build feature converters that process only the necessary features.To synchronize feature requirements between the root and leaves, model signatures are published as lightweight artifacts. These signatures are aggregated into bundle-level mappings, which are then deployed to the root alongside existing configurations. This deployment follows the same staged delivery process as model rollouts, ensuring consistency and enabling graceful rollbacks.This integration allows the Feature Trimmer to dynamically update feature allowlists on the root, ensuring that only essential features are transmitted. The system is designed to handle frequent model updates and gradual rollouts by using versioned lookups and fallback mechanisms. This ensures that the root's view of required features stays synchronized with the actual models deployed on the leaves. By trimming unneeded features, Pinterest significantly reduced network traffic and improved infrastructure efficiency.
CdXz5zHNQW_Pr67hugpQp.png
Pinterest developed a dedicated candidate generation model for conversion ads to address challenges with offsite conversion data sparsity and noise. This model differs from previous engagement-based systems by focusing on lower-funnel conversions. The initial launch in 2023 yielded significant improvements in both conversion and engagement metrics, including a higher clickthrough rate. Further iterations in 2025 delivered even greater conversion value and enhanced advertiser return on ad spend. To combat data sparsity, the model is trained across all shopping surfaces using a multi-surface approach. It supplements primary conversion signals with onsite engagement data, re-weighting click data based on duration to mitigate noise. Harder negatives, such as ad impressions with no engagement, are used for more robust contrastive learning. The model incorporates user-side features capturing real-time intent and long-term preferences, alongside Pin-side features for semantic understanding and performance tracking. A two-tower architecture with DCN v2 and an MLP in parallel cross layers enhances feature interaction modeling and retrieval quality. The model evolved from a multi-head design to a unified multi-task architecture, allowing direct benefit from multi-task optimization during serving. An advertiser-level loss function was introduced to provide a more stable granularity for conversion signals, leading to substantial recall improvements. This new model successfully increased shopping conversion volume and improved advertiser performance while enhancing the user shopping experience.
CdXz5zHNQW_iZkUUBsGZ2.png
Pinterest uses content understanding to drive distribution and engagement, requiring insight into images and outbound links. The core problem is URL normalization, where identical product pages appear under varied URLs due to tracking parameters. This redundancy leads to wasted computational resources through repeated fetching and processing. Item canonicalization aims to unify identical items represented by different URLs, crucial for shopping catalogs. When item IDs are absent, advanced URL normalization is vital for deduplication.The Minimal Important Query Param Set (MIQPS) algorithm automatically learns which URL parameters influence content identity. It distinguishes between neutral parameters, which don't affect page content, and non-neutral parameters, which do. While static rules work for well-known platforms, Pinterest's vast domain set requires a dynamic, data-driven approach.The MIQPS algorithm operates in three steps. First, it collects a corpus of observed URLs per domain from Pinterest's ingestion pipeline. Second, URLs are grouped by their query parameter pattern, ensuring parameters are analyzed in their specific context. This prevents misclassifying a parameter based on a different URL type.Finally, for each parameter within a pattern, the algorithm empirically tests its importance. It samples URLs with distinct parameter values and computes content IDs for both the original and modified (parameter-removed) URLs. If removing the parameter changes the content ID in a significant percentage of samples, it's classified as non-neutral and retained. Otherwise, it's deemed neutral and can be safely stripped for normalization. Each merchant domain receives its own MIQPS map, accounting for domain-specific parameter meanings.
CdXz5zHNQW_WVip85jMBw.png
CdXz5zHNQW_RcLxSqw9JO.png
CdXz5zHNQW_acxjx5IRwX.png
Large online platforms face the challenge of organizing billions of items into navigable shopping collections. Historically, these collections relied on user search history and manual curation. However, multimodal large language models (LLMs) now enable generating collections directly from content, while still considering user search patterns. This paper introduces Pinlanding, a production pipeline for shopping collection generation. Pinlanding comprises four components: understanding user search intent, building a shopping collection vocabulary using LLMs, constructing feeds from attributes, and evaluating/evolving the system. User interaction data helps characterize shopping intents, revealing both high-volume searches and emerging long-tail conversational queries. A vision-language model generates initial product attributes, which are then curated into a compact vocabulary using statistical filtering, embedding-based clustering, and LLM-assisted review. A CLIP-style dual-encoder model is trained for scalable attribute assignment, efficiently mapping products to attributes. Ray is used for scalable batch inference in attribute assignment, and Spark constructs feeds by scoring product-topic relevance. The CLIP-based classifier shows superior performance on a fashion attribute prediction benchmark. Human evaluation demonstrates that Pinlanding significantly improves precision in collection quality compared to traditional methods. The system has led to a four-fold increase in unique shopping topics and a 35% improvement in search performance. Future work involves integrating social trends and developing an AI-agent layer to handle emergent composite concepts.
CdXz5zHNQW_plPICGLX7O.png
Pinterest Search developed a method to enhance search relevance evaluation using Large Language Models (LLMs). Traditional relevance measurement relied on costly human annotations, limiting the scale and sensitivity of A/B experiments. To address this, they fine-tuned open-source LLMs on human-labeled data to predict Pin relevance to queries. This LLM-based approach treats relevance prediction as a multiclass classification problem, utilizing features like Pin titles, descriptions, and image captions.They adopted a stratified query sampling design, which significantly reduces the Minimum Detectable Effect (MDE) by an order of magnitude. This new methodology enables the measurement of heterogeneous treatment effects and improves evaluation efficiency. The LLM labeling process significantly lowers costs and time, allowing for larger and more representative sample sizes.After fine-tuning, the LLM-based relevance model generates relevance scores, which are then used to compute metrics like sDCG@K. Rigorous validation showed high alignment between LLM-generated labels and human annotations, with an exact match rate of 73.7% and strong rank-based correlations. This alignment holds even for queries of different popularity segments.The LLM-based relevance assessment proved effective for non-English queries as well, maintaining strong correlations and low bias. By transitioning to LLM-based relevance assessment, Pinterest Search has been able to scale up their evaluation query sets and improve the quality of relevance metrics for online experiment evaluation. This has led to a significant reduction in manual annotation efforts and enhanced the overall efficiency of their A/B testing process. The chosen LLM, XLM-RoBERTa-large, offers a good balance of prediction quality and inference efficiency.
CdXz5zHNQW_fbv8G1VHoa.png
Pinterest uses a metric called prevalence to measure policy-violating content, defined as the percentage of all views that went to harmful content. Prevalence complements user reports by identifying under-reported harms and tracking trends. Historically, reliance on human review for measuring prevalence was slow and expensive. To address this, Pinterest developed an AI-assisted workflow for daily prevalence measurement. This involves sampling user impressions and using a multimodal LLM for large-scale labeling. The LLM, guided by expert prompts and subject matter experts, significantly reduces latency and cost while maintaining accuracy. Prevalence is calculated daily, with confidence intervals, and can be broken down by policy areas, sub-policies, and content surfaces. The system uses risk scores from enforcement models for efficient sampling, but these scores do not act as labels. Inverse-probability weighting ensures the prevalence statistic accurately reflects user impressions over time, even with enforcement threshold changes. Machine learning is crucial for unbiased sampling and efficient labeling, allowing for faster risk detection and proactive responses. This data-driven approach enables quicker product iterations, informed policy development, and strategic decision-making, including setting goals and allocating resources effectively. Challenges like wide confidence intervals for rare categories or policy drift are managed through adaptive sampling and continuous monitoring. Future plans include expanding pivoting capabilities, optimizing LLM usage, and refining human-in-the-loop processes for enhanced accuracy and reduced bias.
Android end-to-end testing builds at Pinterest were slow and unreliable due to unbalanced test shards and platform limitations. The team first evaluated third-party solutions but found them inadequate for their needs. They decided to build an in-house testing platform called PinTestLab, hosted on EC2 emulators. This platform allowed for complete control over the testing stack and infrastructure.The core innovation is a runtime-aware sharding mechanism. This system uses historical test duration and stability data to pack tests into shards. The goal is to ensure that each shard has a similar total runtime. This approach differs from simply balancing the number of tests per shard.Previously, package-based sharding led to imbalances where a single slow shard would delay the entire build. Even simple time-based sorting failed to account for emulator idle time. The new runtime-aware sharding algorithm works by sorting tests by average runtime and then greedily assigning each test to the emulator projected to finish earliest. This keeps all emulators busy and minimizes the time difference between the fastest and slowest shards.The impact of this solution has been significant. End-to-end build times were reduced by nine minutes, a 36% improvement. The runtime of the slowest shard decreased by 55%. The time difference between the fastest and slowest shards was dramatically compressed from 597 seconds to just 130 seconds. This boosts developer velocity by providing faster and more reliable feedback.
CdXz5zHNQW_7VB873V6rz.png
Pinterest's ML training platform, MLEnv, encountered a significant performance drop after a PyTorch version upgrade. This issue led to a more than 50% reduction in training throughput. The debugging process began by examining the GPU roofline throughput. This measurement revealed a 20% performance decrease even when excluding the data loader. Further analysis focused on individual model modules to pinpoint the source of the slowdown. A specific transformer module, module A, was identified as the primary culprit. The PyTorch profiler showed that CompiledFunctions, previously present, were now missing for this module in the upgraded version.Investigation into torch.compile revealed a log indicating that a non-infrastructure PyTorch dispatch mode was present, which torch.compile did not support. Minimal reproducible scripts confirmed that this issue manifested specifically within the trainer class. The problematic component was identified as a context manager used for FLOPs counting, enabled by default. Disabling this context manager resolved the torch.compile issue, restoring CompiledFunctions. However, this fix did not improve end-to-end throughput.The focus shifted back to the data loading and distributed training aspects, ruling out Ray.data as the cause by observing the same GPU roofline throughput issues even when running as a native PyTorch application. Several observations pointed to intermittent slow iterations, a straggler effect during synchronization, and a peculiar behavior where enabling Nvidia's Nsight Systems profiler eliminated the slowness. Testing on a single GPU confirmed distributed training was not the root cause. Disabling torch.compile entirely in the Ray setup restored original throughput, suggesting that graph breaks within torch.compile were related to the slowdowns.Creating a minimal reproducible model with extensive graph breaks led to the observation of recurring slow iterations. Nsight Systems traces revealed that the main training thread was holding the Global Interpreter Lock (GIL) during these slow iterations, but this did not explain the entire pause. Further analysis using the Linux perf tool and visualizing the traces with chrome://tracing highlighted a suspicious Python process. This process was executing an expensive computation, specifically a Linux kernel call named smap_gather_stats, which gathers virtual memory statistics.
CdXz5zHNQW_ahqFK2Jga1.png
CdXz5zHNQW_JMlsyqEFEB.png
CdXz5zHNQW_dc6w46JhEJ.png
Pinterest's Data Engineering team is building a new massive scale data processing platform to replace their current Hadoop-based platform, Monarch. The team explored Kubernetes-based systems as a replacement due to their growing popularity and increasing adoption in the Big Data community. The new platform had to meet certain criteria, including extensive support for containers, execution of Pinterest's custom Spark fork, and lower operational and maintenance costs. The team performed a comprehensive evaluation of running Spark on various platforms and leaned towards Kubernetes-focused frameworks due to their advantages, including container-based isolation and security, ease of deployment, and built-in frameworks. Kubernetes provides more fine-grained support for container management and deployment than other systems, but lacks built-in support for data management, storage, and processing. The team's current deployment model in Hadoop is cumbersome, and they are moving towards a more straightforward approach using Terraform, container images, and Helm. The new platform will leverage Kubernetes and EKS to replace Monarch, introducing several challenges, including integrating EKS into the existing Pinterest environment and finding replacements for Hadoop components. The team has built a new platform, Moka, which is able to process batch Spark workloads that only access non-sensitive data, and will add more functionality in the future. The initial high-level design of Moka includes a system that can process batch Spark workloads, with jobs submitted and processed through a series of components, including Spinner, Archer, and the Spark Operator. The team will provide more details on the core application-focused aspects of their platform in the next part of their blog series.
CdXz5zHNQW_bbfzbQhJcm.png
CdXz5zHNQW_vBYaC4X7rO.png
CdXz5zHNQW_OYKi1HZH8r.png
CdXz5zHNQW_kxoAAaP5LS.jpeg
CdXz5zHNQW_I5dnAJn3pO.png
Pinterest is a unique platform where users, known as Pinners, come to find inspiration and ideas for various aspects of their lives. The platform's goal is to provide a personalized experience, showing users content that is relevant to their interests and searches. Pinterest's approach to personalization is different from other platforms, as it prioritizes quality time over time spent on the platform. The company believes that a balance between different approaches to content ranking is necessary, incorporating explicit engagement signals, community guidelines, and survey-based personalization. Pinterest uses surveys to gather feedback from users and create a healthier and more inspirational experience. The platform's surveys are designed to be rigorous and effective, with a team of experts ensuring that the surveys are well-designed and useful. The surveys have been instrumental in helping Pinterest create a positive and inspirational experience for users, with recent research showing that the platform leads the industry in terms of its impact on user wellbeing. Pinterest's approach to personalization is guided by the principles of the Inspired Internet Pledge, which calls for companies to prioritize user wellbeing and create a healthier internet experience. By using surveys and prioritizing user wellbeing, Pinterest is proving that it is possible to create a safer and healthier online experience. Overall, Pinterest's unique approach to personalization and its commitment to user wellbeing set it apart from other social media platforms.
CdXz5zHNQW_xMjUEWeEAQ.png
CdXz5zHNQW_P7QrX8S0r6.png