Orivel Orivel
Open menu

Latest Tasks & Discussions

Browse the latest benchmark content across tasks and discussions. Switch by genre to focus on what you want to compare.

Benchmark Genres

Model Directory

Summarization

OpenAI GPT-5.2 VS Google Gemini 2.5 Pro

Summarize a Passage on the History and Science of Urban Heat Islands

Read the following passage carefully and write a summary of no more than 250 words. Your summary must preserve all of the key points listed after the passage and must be written as a single cohesive essay (not bullet points). --- BEGIN PASSAGE --- Urban heat islands (UHIs) are metropolitan areas that experience significantly higher temperatures than their surrounding rural counterparts. This phenomenon, first documented by amateur meteorologist Luke Howard in the early nineteenth century when he observed that central London was consistently warmer than its outskirts, has become one of the most studied aspects of urban climatology. Howard's pioneering temperature records, maintained between 1807 and 1830, revealed that the city center could be as much as 3.7 degrees Fahrenheit warmer than nearby countryside locations. While his measurements were rudimentary by modern standards, they laid the groundwork for more than two centuries of scientific inquiry into how cities alter their local climates. The primary causes of urban heat islands are well understood by contemporary scientists. First, the replacement of natural vegetation and permeable soil with impervious surfaces such as asphalt, concrete, and roofing materials dramatically changes the thermal properties of the landscape. These materials have low albedo, meaning they absorb a large fraction of incoming solar radiation rather than reflecting it back into the atmosphere. Concrete, for example, reflects only about 10 to 35 percent of sunlight depending on its age and composition, while fresh asphalt reflects as little as 5 percent. In contrast, grasslands and forests typically reflect between 20 and 30 percent of incoming solar energy. Second, the geometric arrangement of buildings in cities creates what scientists call "urban canyons," narrow corridors between tall structures that trap heat through multiple reflections and reduce wind flow, limiting the natural ventilation that would otherwise help dissipate accumulated warmth. Third, anthropogenic heat sources — including vehicles, air conditioning units, industrial processes, and even the metabolic heat of dense human populations — contribute additional thermal energy to the urban environment. In large cities like Tokyo, anthropogenic heat output can exceed 1,590 watts per square meter in commercial districts during winter months, a figure that rivals the intensity of incoming solar radiation on a clear day. The consequences of urban heat islands extend far beyond mere discomfort. Public health researchers have established strong links between elevated urban temperatures and increased rates of heat-related illness and mortality. A landmark study published in 2014 by the Centers for Disease Control and Prevention found that extreme heat events in the United States caused an average of 658 deaths per year between 1999 and 2009, with urban residents disproportionately affected. Vulnerable populations — including the elderly, young children, outdoor workers, and individuals with pre-existing cardiovascular or respiratory conditions — face the greatest risks. During the catastrophic European heat wave of 2003, which killed an estimated 70,000 people across the continent, mortality rates were markedly higher in densely built urban cores than in suburban or rural areas. Beyond direct health impacts, UHIs also degrade air quality by accelerating the formation of ground-level ozone, a harmful pollutant created when nitrogen oxides and volatile organic compounds react in the presence of heat and sunlight. Cities experiencing intense heat island effects often see ozone concentrations spike well above safe thresholds on hot summer days, triggering respiratory distress in sensitive individuals and contributing to long-term lung damage across broader populations. Energy consumption patterns are also profoundly influenced by the urban heat island effect. As temperatures climb, demand for air conditioning surges, placing enormous strain on electrical grids and driving up energy costs for residents and businesses alike. The U.S. Environmental Protection Agency estimates that for every 1 degree Fahrenheit increase in summer temperature, peak electricity demand in a city rises by 1.5 to 2 percent. Across the United States, the additional cooling energy required because of urban heat islands is estimated to cost residents and businesses approximately $1 billion per year. This increased energy consumption also creates a feedback loop: power plants burn more fossil fuels to meet demand, releasing additional greenhouse gases and waste heat that further warm the atmosphere, both locally and globally. In this way, urban heat islands are not merely a symptom of urbanization but an active contributor to the broader challenge of climate change. Fortunately, a growing body of research has identified effective mitigation strategies. Cool roofs — roofing materials engineered to reflect more sunlight and absorb less heat — can reduce rooftop temperatures by up to 60 degrees Fahrenheit compared to conventional dark roofs. Green roofs, which incorporate layers of vegetation atop buildings, provide additional benefits including stormwater management, improved air quality, and habitat for urban wildlife. At the street level, increasing tree canopy coverage has proven to be one of the most cost-effective interventions. A mature shade tree can reduce local air temperatures by 2 to 9 degrees Fahrenheit through a combination of shading and evapotranspiration, the process by which plants release water vapor into the atmosphere, effectively cooling the surrounding air. Cities such as Melbourne, Australia, and Singapore have launched ambitious urban greening programs, with Melbourne aiming to increase its canopy coverage from 22 percent to 40 percent by 2040. Cool pavements, which use lighter-colored or reflective materials for roads and sidewalks, represent another promising approach, with pilot programs in Los Angeles showing surface temperature reductions of up to 10 degrees Fahrenheit on treated streets. Policy frameworks are beginning to catch up with the science. In 2022, the city of Paris adopted a comprehensive urban cooling plan that mandates green roofs on all new commercial buildings, requires permeable surfaces in at least 30 percent of new developments, and commits to planting 170,000 new trees by 2030. New York City's CoolRoofs program, launched in 2009, has coated more than 10 million square feet of rooftop with reflective material, and the city estimates the initiative has reduced peak cooling energy demand by 10 to 30 percent in participating buildings. Meanwhile, Medellín, Colombia, has gained international recognition for its "Green Corridors" project, which transformed 18 roads and 12 waterways into lush, tree-lined corridors, reducing local temperatures by up to 3.6 degrees Fahrenheit and earning the city a 2019 Ashden Award for its innovative approach to climate adaptation. These examples demonstrate that with political will and informed planning, cities can meaningfully reduce the intensity of their heat islands and improve quality of life for millions of residents. --- END PASSAGE --- Key points your summary MUST include: 1. Definition of urban heat islands and their historical discovery by Luke Howard. 2. At least three causes of UHIs (impervious surfaces with low albedo, urban canyon geometry, and anthropogenic heat sources). 3. Health consequences, including mention of vulnerable populations and the 2003 European heat wave. 4. Impact on energy consumption and the feedback loop with greenhouse gas emissions. 5. At least three mitigation strategies (e.g., cool roofs, green roofs, increased tree canopy, cool pavements). 6. At least one specific city-level policy example (Paris, New York City, or Medellín). Constraints: - Maximum 250 words. - Written as a cohesive essay, not bullet points. - Do not introduce information not present in the passage.

40
Mar 23, 2026 09:20

Summarization

Google Gemini 2.5 Pro VS Anthropic Claude Opus 4.6

Summarize a Town-Hall Debate on Urban Flood Resilience

Read the source passage below and write a concise summary in 180 to 230 words. Your summary must be in prose, not bullet points. It should preserve the main decisions under consideration, the strongest arguments from multiple sides, the key factual constraints, and the unresolved trade-offs. Do not quote directly. Do not add outside facts or opinions. Source passage: Riverton, a riverfront city of about 320,000 residents, has spent the past decade celebrating its downtown revival. Old warehouses became apartments, a tram line linked the train station to the arts district, and three blocks of former parking lots were converted into a public market and a plaza that hosts festivals almost every weekend from April through October. Yet the same river that gave Riverton its identity has become its most visible threat. In the last six years, heavy rain events that local engineers once called “hundred-year storms” have happened often enough that residents now speak of them by the names of the neighborhoods they flooded. Insurance payouts have climbed, two elementary schools have closed for repeated repairs, and a wastewater pumping station narrowly avoided failure during the storm last September. The city council has convened a special town-hall meeting to decide which flood-resilience plan should go forward first, knowing that no single plan can be fully funded this budget cycle. City engineer Mara Singh opens with a presentation that frames the options. Plan A would build a continuous floodwall and earthen berm system along the most exposed 5.4 miles of riverfront, protecting downtown, the market, and several dense residential blocks. It is the most expensive option at an estimated 186 million dollars, not including property acquisition for easements, but it offers the clearest reduction in immediate flood risk to the taxable core of the city. Plan B would focus instead on distributed green infrastructure: widening stormwater channels, adding permeable pavement on 60 blocks, restoring wetlands in two low-lying parks, subsidizing rain gardens on private lots, and replacing undersized culverts in the northeast basin. Its initial cost is lower, at 118 million dollars, and planners argue it would reduce runoff citywide while improving summer heat conditions and neighborhood green space. However, Singh warns that green measures are harder to model, take years to mature, and may not adequately protect downtown during the most extreme river surges. Plan C is a managed-retreat and buyout program targeting the 1,100 homes and small businesses that flood repeatedly in the lowest areas. It would cost about 94 million dollars in direct purchases and relocation support, though that figure could rise if property values increase or if the city provides replacement affordable housing. Supporters say retreat avoids rebuilding in places that will remain dangerous; opponents call it socially disruptive and politically unrealistic. The finance director, Elena Brooks, explains why the council cannot simply combine all three plans. Riverton can responsibly borrow about 130 million dollars over the next five years without risking a credit downgrade that would raise costs for schools, transit, and routine infrastructure. The city expects roughly 35 million dollars in state and federal grants, but those are competitive and may require local matching funds. Annual maintenance also differs sharply: the floodwall system would require inspections, pump operations, and periodic reinforcement; green infrastructure would need dispersed upkeep across many sites; buyouts would reduce some future emergency costs but would remove properties from the tax rolls unless the land is repurposed. Brooks emphasizes that “cheapest upfront” does not mean “cheapest over thirty years,” especially as repeated recovery spending is already straining reserves. Public comment quickly reveals that the debate is not only technical. A downtown restaurant owner, Luis Ortega, says another major flood season could destroy small businesses just as tourism has returned. He favors Plan A, arguing that protecting the commercial center protects the city’s sales-tax base, jobs, and civic confidence. In contrast, Tasha Green, who lives in the northeast basin, says Riverton has historically underinvested in outer neighborhoods while prioritizing downtown optics. She supports Plan B because street flooding there often happens even when the river does not overtop its banks. Green notes that children in her area walk through pooled water near fast traffic after storms, and several basement apartments have persistent mold. For her, a wall on the riverfront would symbolize “protecting postcards, not people.” A housing advocate, Daniel Cho, urges the council not to dismiss Plan C simply because it is uncomfortable. He describes families who have replaced furnaces, drywall, and cars multiple times in a decade, often with partial insurance coverage or none at all. In his view, repeatedly repairing homes in the highest-risk blocks is both cruel and fiscally irrational. Yet he also warns that any buyout program without guaranteed relocation options inside Riverton would accelerate displacement, especially for renters, seniors, and residents with limited English proficiency who often receive information last. Several speakers echo that fear. A school principal points out that if entire clusters of families move away, enrollment could fall enough to threaten already fragile neighborhood schools. Environmental scientists from the regional university complicate the picture further. Professor Nia Feld presents modeling showing that a floodwall could increase water velocity downstream unless paired with upstream storage or bypass measures, potentially shifting risk to two smaller municipalities. She says Riverton might face legal and political conflict if it acts alone. Another researcher notes that restored wetlands can absorb moderate stormwater volumes and provide habitat and cooling benefits, but they are not magic sponges; in prolonged saturated conditions, their marginal benefit declines. Both scientists argue that climate uncertainty makes single-solution thinking dangerous. They recommend sequencing investments so that whichever major plan is chosen first does not foreclose later adaptation. Labor leaders and business groups unexpectedly agree on one point: timing matters. The construction trades council says Plan A would create the largest number of immediate union jobs and could be phased visibly, which helps maintain public support. A representative of small manufacturers, however, says years of riverfront construction might disrupt deliveries and reduce customer access. Supporters of Plan B say its many smaller projects could spread contracts across neighborhoods and local firms rather than concentrating them in one corridor. Parks staff add that wetland restoration would temporarily close popular recreation areas, though they argue the parks would become more usable in the long run because trails now wash out repeatedly. Several council members focus on governance and trust. Councilor Priya Desai says residents are tired of pilot projects announced with enthusiasm and then neglected once ribbon-cuttings are over. She worries Plan B’s success depends on maintenance discipline the city has not always shown. Councilor Ben Hall, whose district includes much of downtown, argues that a city that cannot protect its core will struggle to fund anything else in the future. Councilor Marisol Vega counters that buyouts have failed elsewhere when governments treated them as real-estate transactions instead of long-term community transitions with counseling, tenant protections, and land-use planning. She says Riverton should not pretend relocation is cheap just because the capital line looks smaller. By the end of the evening, no consensus has emerged, but a possible compromise begins to take shape. The mayor asks staff to analyze a first-phase package that would start a shortened version of Plan B in the northeast basin and at critical drainage chokepoints citywide, while also advancing design, permitting, and land acquisition for the most urgent downtown floodwall segments rather than full construction. The package would also create a voluntary pilot buyout program for the most repeatedly flooded cluster of 120 properties, coupled with a requirement that any purchased rental units be replaced with affordable housing within city limits. This hybrid approach might fit within the borrowing cap if Riverton wins at least part of the anticipated grants, but staff caution that phasing can increase total cost and may disappoint everyone by delaying the sense of protection any single strategy promises. As residents file out, the practical question is no longer whether Riverton should adapt, but how to distribute protection, sacrifice, and time. The meeting has made one fact plain: flood resilience is not only an engineering challenge but also a test of what the city owes to neighborhoods that generate revenue, neighborhoods that have long absorbed neglect, and households being asked to imagine that safety may require moving away from places they have every reason to call home.

33
Mar 23, 2026 09:11

Analysis

Google Gemini 2.5 Pro VS OpenAI GPT-5.2

Evaluating Evidence in a Product Recall Decision

A consumer electronics company, VoltTech, manufactures a popular portable phone charger called the PowerPak 3000. Over the past six months, the company has received the following reports and data: 1. Customer complaints: 47 reports of the device overheating during use, out of approximately 820,000 units sold. Of these, 12 customers reported minor burns, and 3 reported small fires that were quickly contained. 2. Internal testing: VoltTech's quality assurance team tested 500 units from recent production batches. They found that 2.4% of units exhibited higher-than-normal thermal output under sustained maximum load, but all remained within the technical safety threshold defined by the relevant UL certification standard. 3. A competitor's similar product was recalled last month for a comparable overheating issue, generating significant media coverage and public concern about portable charger safety in general. 4. An independent consumer safety blog published an article claiming the PowerPak 3000 has a "dangerous design flaw," based on teardown analysis of a single unit purchased from a third-party reseller. VoltTech has not verified whether that unit was genuine or counterfeit. 5. VoltTech's legal team estimates that a voluntary recall would cost approximately $14 million, while continuing sales without action and facing potential future litigation could cost between $2 million (if no serious incidents occur) and $40 million (if a serious injury or property damage lawsuit succeeds). Analyze the evidence above and recommend whether VoltTech should issue a voluntary recall, implement a lesser corrective action (such as a firmware update, warning label addition, or exchange program), or take no action. Justify your recommendation by evaluating the strength and limitations of each piece of evidence, weighing the risks, and explaining your reasoning clearly.

42
Mar 21, 2026 08:06

Business Writing

OpenAI GPT-5.2 VS Google Gemini 2.5 Pro

Write a Client-Facing Email Explaining a Significant Project Delay

You are a project manager at a mid-sized software consulting firm. Your team has been developing a custom inventory management system for a retail client, GreenLeaf Stores. The project was originally scheduled to deliver its first production-ready release on August 15, but due to unexpected technical complications with integrating the client's legacy database and the departure of a senior developer, the delivery will be delayed by approximately six weeks (new target: September 26). Your client contact is Dana Morales, VP of Operations at GreenLeaf Stores. Dana has been supportive but is under pressure from her own leadership to have the system operational before the holiday shopping season begins in mid-October. Write a professional email to Dana that accomplishes all of the following: 1. Clearly communicates the delay and the new expected delivery date. 2. Briefly explains the reasons for the delay without making excuses or assigning blame. 3. Acknowledges the impact on GreenLeaf's business timeline and demonstrates empathy. 4. Proposes at least two concrete mitigation steps your firm will take to minimize further risk and protect the October operational deadline. 5. Maintains a tone that is honest, confident, and relationship-preserving. The email should include a subject line and be between 250 and 400 words (excluding the subject line). Do not use placeholder text such as "[insert name here]." Write the complete, ready-to-send email.

62
Mar 20, 2026 15:18

Summarization

Google Gemini 2.5 Pro VS Anthropic Claude Sonnet 4.6

Summarize a Public Consultation Brief on Nighttime Delivery in a Historic City Center

Read the following consultation brief and write a concise summary for a city council member who has not read the document. Your summary must: - be 220 to 300 words long - use neutral, non-promotional language - explain the problem the city is trying to solve - capture the main evidence and viewpoints from supporters and critics - include the proposed pilot program, its safeguards, and how success would be measured - mention at least three specific operational details or numbers from the brief - avoid quoting full sentences from the source - not add facts or opinions not supported by the source Source passage: The City of Larkhaven is considering a 12-month pilot program that would allow a limited number of nighttime deliveries in the Old Market district, a dense mixed-use neighborhood known for narrow streets, heritage buildings, restaurants, small grocers, apartments above shops, and heavy daytime foot traffic. At present, most commercial deliveries are concentrated between 7:00 a.m. and 2:00 p.m. As a result, box trucks often double-park on streets that were laid out long before modern freight vehicles existed. Delivery drivers unload beside bus stops, riders on bicycles weave into traffic to pass stopped trucks, and pedestrians spill off crowded sidewalks when hand carts block storefronts. According to the city’s transportation department, freight activity is not the largest source of congestion in Old Market, but it is among the most disruptive because the disruptions occur on the narrowest streets and at the busiest times. A staff report prepared for the council argues that shifting some deliveries to late evening or overnight hours could reduce daytime conflicts without increasing the total number of trips. The proposal would not create new delivery demand; instead, it would move selected restocking trips to lower-traffic periods. Staff cite examples from other cities where off-hour deliveries shortened average unloading times because drivers could park legally closer to destinations and complete routes more predictably. The report also notes potential environmental benefits from smoother driving speeds and less idling while searching for curb space. However, staff acknowledge that the same studies found uneven results when neighborhoods had many residents living directly above commercial premises, especially where building insulation was poor. The draft pilot would cover only the four-block core of Old Market and would limit participation to 18 businesses in its first phase. Eligible businesses would include food retailers, pharmacies, and hospitality venues that already receive at least four deliveries per week. Participating carriers would need to use vehicles no larger than 7.5 tons gross weight and comply with a quiet-delivery code. That code would prohibit metal roll cages, require rubberized cart wheels, ban unloading with engine idling beyond two minutes, and require drivers to complete noise-awareness training. Routine delivery windows under the pilot would run from 9:30 p.m. to 6:00 a.m., but no unloading could begin after midnight within 20 meters of a residential entrance unless the destination business had submitted a building-specific mitigation plan. To address concerns about resident sleep disturbance, the city proposes several safeguards. First, the pilot would exclude streets with documented nighttime noise complaints above the district median during the previous 18 months. Second, each participating business would have to designate an on-site receiver so drivers would not need to buzz apartments or repeatedly knock on locked service doors. Third, the city would install temporary sound monitors at 12 locations and publish monthly readings, along with a log of complaints, parking citations, and observed curb-blocking incidents. Fourth, the pilot could be suspended on any block where overnight complaints exceeded a trigger threshold for two consecutive months. The threshold in the draft is six verified complaints per 100 residents, though staff say this number is open to revision after public comment. Business groups strongly support the pilot. The Old Market Merchants Association says morning deliveries frequently arrive after shops open, forcing staff to restock shelves while also serving customers. Restaurant owners argue that receiving produce and beverages at dawn or late night would free curb space during lunch preparation and reduce the need for workers to drag pallets through crowded dining streets. A coalition of independent grocers adds that more predictable delivery times could cut spoilage for chilled goods, because drivers would spend less time stuck in queues. Several carriers also support the plan, saying a truck can sometimes spend more time circling for legal curb access than actually unloading. They argue that if routes become more reliable, fewer backup vehicles may be needed to complete the same volume of deliveries. Resident organizations are divided. Some acknowledge that daytime freight activity has become chaotic and that blocked sidewalks are especially difficult for older adults, parents with strollers, wheelchair users, and delivery workers on cargo bikes. Others say the burden is being shifted from shoppers to people trying to sleep. The Old Market Tenants Forum submitted comments noting that many apartments have single-glazed windows and bedrooms facing service alleys. The forum argues that even if average noise readings stay within acceptable ranges, repeated short bursts from tail lifts, rolling containers, reversing alarms, and late conversations can still wake residents. Preservation advocates have raised a related concern: because many buildings are protected, retrofitting loading areas or installing acoustic barriers may be expensive, restricted, or visually inappropriate. Labor representatives have offered conditional support but say the pilot should not depend on unpaid schedule flexibility from retail staff or unsafe expectations for drivers. The local drivers’ union says quieter equipment is welcome, but nighttime operations can create pressure to unload faster with fewer workers present. They want clear rules on staffing, access, lighting, and restroom availability. A union representing shop employees says receiving deliveries at 5:00 a.m. should not become an informal expectation for junior workers without revised contracts, transport allowances, or secure entry procedures. City staff responded by stating that labor conditions would be monitored through employer attestations and random compliance checks, though details remain limited in the current draft. The consultation brief includes preliminary cost estimates. The city expects to spend about $420,000 over 12 months: roughly $160,000 for monitoring equipment and data analysis, $110,000 for curbside signage and temporary loading zone adjustments, $90,000 for program administration and inspections, and $60,000 for driver training subsidies and business onboarding. Staff propose funding the pilot from the existing mobility innovation budget rather than from the general fund. They argue that if daytime curb conflicts decline, the city may avoid or defer more expensive street redesigns. Critics reply that the estimate may be incomplete because it does not clearly price enforcement during overnight hours or any mitigation measures for affected residents. The brief also explains why the city is pursuing a pilot instead of a permanent rule change. Freight patterns vary sharply by street, season, and business type, and council members previously rejected a citywide nighttime delivery ordinance as too broad. Staff now argue that a smaller trial with block-by-block reporting would generate better local evidence. The proposed evaluation framework would compare pilot streets with similar non-pilot streets using measures such as average unloading duration, illegal parking observations, daytime travel speeds for buses, complaint rates, worker injury reports, and business delivery reliability. The city would also survey residents, drivers, and participating businesses at three points: before launch, at six months, and near the end of the trial. A final recommendation would return to council only if the data showed meaningful daytime benefits without disproportionate nighttime harms. At a recent public meeting, council members signaled interest but asked for revisions. One requested a stricter cap on the number of participating vehicles per night. Another asked staff to clarify whether electric refrigeration units would be required for chilled-food suppliers, since diesel-powered units can create a persistent hum even when engines are off. A third questioned whether the complaint trigger should be based on residents, dwelling units, or building frontages, noting that each method could produce different outcomes on mixed-use blocks. Staff said they would revise the draft before the formal vote next month and might narrow the eligible street list further if consultation feedback shows concentrated concern. In short, the debate is not simply about whether goods should move at night. It is about whether carefully managed off-hour deliveries can reduce visible daytime disorder in a fragile, busy district without transferring the costs to residents, workers, or historic buildings. The consultation asks respondents to comment on the proposed hours, business eligibility rules, quiet-delivery standards, complaint thresholds, labor protections, and evaluation metrics. Written comments remain open until the 28th of this month, after which staff will publish a response summary and a revised pilot design for council consideration.

51
Mar 20, 2026 11:21

Coding

Google Gemini 2.5 Pro VS OpenAI GPT-5.2

Implement a Concurrent Rate Limiter with Sliding Window and Priority Queues

Design and implement a thread-safe rate limiter in Python that supports the following features: 1. **Sliding Window Rate Limiting**: Rather than using fixed time windows, implement a true sliding window algorithm. Each client (identified by a string key) is allowed at most `max_requests` requests within any rolling window of `window_seconds` seconds. 2. **Priority Levels**: Each request has a priority level (integer 1-5, where 1 is highest priority). When the rate limit is reached for a client, lower-priority requests (higher number) should be rejected first. Specifically, if a new request with priority P arrives and the window is full, the limiter should check whether any request in the current window has a strictly lower priority (higher number) than P. If so, the lowest-priority (highest-numbered) request's slot is "revoked" and the new higher-priority request is admitted. The revoked request should be recorded so it can be reported. If no lower-priority request exists to revoke, the new request is rejected. 3. **Burst Allowance**: Each client may optionally have a burst allowance `burst` (defaulting to 0). This allows up to `burst` additional requests beyond `max_requests` in a window, but only if at least half the window duration has passed since the client's first request in the current window. 4. **Thread Safety**: The rate limiter must be safe to use from multiple threads concurrently. Demonstrate this with a test scenario. 5. **Statistics**: The limiter must track per-client statistics: total requests admitted, total rejected, total revoked (bumped by higher-priority requests), and current window utilization (as a float 0.0 to 1.0). Implement the following interface: ```python class RateLimiter: def __init__(self, max_requests: int, window_seconds: float, default_burst: int = 0): ... def set_client_burst(self, client_id: str, burst: int) -> None: """Override burst allowance for a specific client.""" ... def allow(self, client_id: str, priority: int = 3, timestamp: float = None) -> bool: """ Check if a request is allowed. If timestamp is None, use current time. Returns True if the request is admitted, False if rejected. """ ... def get_stats(self, client_id: str) -> dict: """ Return a dict with keys: 'admitted', 'rejected', 'revoked', 'utilization' """ ... def get_revoked_log(self, client_id: str) -> list: """ Return a list of (timestamp, priority) tuples for revoked requests for the given client, in chronological order. """ ... ``` Provide a complete, runnable implementation along with a demonstration script that: - Creates a limiter with max_requests=5, window_seconds=10.0, default_burst=2 - Simulates a sequence of requests from two clients with varying priorities and timestamps that exercises all features (sliding window expiry, priority revocation, burst activation, and rejection) - Prints the stats and revoked logs for each client at the end - Includes a brief multithreaded test with at least 4 threads making concurrent requests Make sure to handle edge cases such as: - Priority value validation (must be 1-5) - Requests arriving exactly at window boundaries - Multiple revocations in sequence - Burst allowance activating precisely at the half-window mark - Empty or unknown client IDs in stats queries

45
Mar 19, 2026 14:46

System Design

Anthropic Claude Opus 4.6 VS Google Gemini 2.5 Pro

Design a Global URL Shortening Service

Design a public URL shortening service similar to Bitly. The service must let users create short links for long URLs, optionally specify a custom alias if available, and redirect users who visit the short link to the original destination. Include a basic analytics feature that reports total clicks per link and clicks by day for the last 30 days. Assume the following constraints: - 120 million new short links are created per month. - 1.2 billion redirect requests are served per month. - Read traffic is highly bursty, especially for viral links. - The service is used globally and users expect low-latency redirects. - Short links should remain valid for at least 5 years. - Redirect availability target is 99.99 percent. - Analytics may be eventually consistent by up to 10 minutes. - The system should prevent obvious abuse at a basic level, but a full trust and safety platform is out of scope. In your design, cover: - High-level architecture and main components. - Data model and storage choices for link mappings and analytics. - ID or token generation strategy, including custom alias handling. - API design for creating links, redirecting, and fetching analytics. - Caching, partitioning, and replication strategy. - Reliability approach, including failure handling and multi-region considerations. - How you would scale for read-heavy traffic and viral hotspots. - Key trade-offs in consistency, cost, latency, and operational complexity. State any reasonable assumptions you make and justify your choices.

61
Mar 19, 2026 08:02

Showing 1 to 20 of 73 results

Related Links

X f L