Building OpenSocial Apps- P7

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

lượt xem

Building OpenSocial Apps- P7

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Building OpenSocial Apps- P7: Nhà phát triển của Thư viện Series từ Addison-Wesley cung cấp hành nghề lập trình với độc đáo, tài liệu tham khảo chất lượng cao hướng dẫn về các ngôn ngữ lập trình công nghệ mới nhất và họ sử dụng trong công việc hàng ngày của họ. Tất cả các sách trong thư viện của Nhà phát triển được viết bởi chuyên gia công nghệ các học viên những người có kỹ năng đặc biệt tại các tổ chức và trình bày thông tin một cách đó là hữu ích cho các lập trình viên khác....

Chủ đề:

Nội dung Text: Building OpenSocial Apps- P7

  1. 274 Chapter 12 App Life Cycle Managing Your App Once your app is live, you can hide it, publish changes to the code, or delete it. Hiding and Deleting an App When you hide an app, you change the status of the application to “Hidden.”This only stops your app from showing up in search results in the apps gallery ( It does not hide the app from users who already have the app installed. Warning The only way to hide an app from users who already have the app installed or force an uninstall is to delete the app. Hiding the app does not hide it from existing users. If you want to delete an app, click Delete.You will be prompted with a confirmation. Click Yes and the app will be deleted. Making Changes to a Live App (Multiple Versions) Once your app has gone live, there are two versions of it: n Development version n Live version When you click Edit App Source on a live app, you see two links: Dev App and Live App at the bottom of the screen (as shown in Figure 12.7). Figure 12.7 Dev App and Live App selection options. Please purchase PDF Split-Merge on to remove this watermark.
  2. Managing Your App 275 Figure 12.8 Note the &appvers=dev at the end of the URL in the address bar. Your Live version can’t be edited directly.You must edit your source code on the Development version. Any changes are immediately reflected in the Development version and don’t appear in the Live version until the app is republished.When you’re testing or viewing your Development version, you should see &appvers=dev at the end of the app’s URL, as shown in Figure 12.8. So, if you ever want to see the Development version of your app, just append &appvers=dev to the end of the query string for the surface you’re currently viewing. Republishing a Live App You’ve changed your code, tested it, made some improvements, and you’re ready to release version 1.1; now what? Click Publish Changes to start the review process over again. Changing the App Profile/Landing Page When users discover your app in the app gallery or through a friend’s page, they’ll click on your app link and be taken to your app Profile page.This is like a landing page, and it contains that magical button that you want everyone to click: Add This App. To see what your app’s Profile looks like, go to the Canvas page and click More Info at the top of the page. Now, do you see a boring default surface with little more than the basic details? Or something that looks more like the landing page shown in Figure 12.9? This is one area that developers often overlook, but it’s very important.The app’s Profile is the first introduction of a potential user to your app, so you should try to sell your app here in order to turn a potential user into a user.You’ll notice that the large professional app development companies have polished-looking app Profile pages. Please purchase PDF Split-Merge on to remove this watermark.
  3. 276 Chapter 12 App Life Cycle Figure 12.9 App Profile page for iLike (http:/, a popular application. Common tweaks include making the Add This App button larger, adding branding, put- ting up screen shots of the app in action, and just generally making the page more appeal- ing to prospective installs. Editing your app Profile page is similar to the way users “bling out” their MySpace Profile pages, and you’re under the same restrictions.That means no JavaScript, but you can modify CSS and add image, anchor, and various style tags, like bold. To edit the app Profile page, you must first log in to MySpace as the app (not as the developer), click Edit Profile, then click the CSS tab. Inside the CSS box you can put any valid CSS.You can hook your CSS styles into existing elements on the page using their IDs or element types. For example, the Add This App button has an ID of profile_appinstall_button, so you can style it using the # CSS selector. Some other useful element IDs are found in Table 12.1, and you can use Firebug or view the source of the page to see all the markup on the page. Another option is to add custom HTML elements to the About section. Inside the Edit Profile page click the About tab; inside the box you can add HTML elements including and tags. If any of the tags have a class attribute, you can add the class definition into the CSS markup under the CSS tab. Here’s an example of how we spiffed up the Tic-Tac-Toe app Profile. First, let’s look at the About section: Please purchase PDF Split-Merge on to remove this watermark.
  4. Managing Your App 277 Table 12.1 CSS Selectors in MySpace CSS Selector HTML Element #profile_appinstall_button{} Add This App button #mainLayout{} Main container for the contents of the Profile; doesn’t include the header or footer of the page or the gray (by default) background #profile_appdetail{} Container for the top left portion of the Profile, including the app’s icon, developers, num- ber of installs, and categories #profile_appinstall{} Container for the top right portion of the Profile; includes the Add This App button #profile_aboutMe{} Container for the bottom portion of the Profile, from “About [app name]” to above the forums #profile_forums{} Container for the forum links body{} The body element for the page, useful for modifying the background color and image The game that’s sweeping the world! Features: Custom backgrounds! Challenge friends! Play the computer! Click the Add this App button above to play now! Then the CSS section: body{ background-image:url(; } #profile_appinstall_button{ background-color:#1E4C9F; border:solid 5px #0cf; color:White; font-family:Verdana; font-size:28px; Please purchase PDF Split-Merge on to remove this watermark.
  5. 278 Chapter 12 App Life Cycle padding:10px; } .ttt_img{ float:left; } .ttt_text{ font-family:Verdana; font-size:18px; } .ttt_text ul{ list-style-position: inside; text-indent: 20px; } .clear{ clear:both; } The final product is shown in Figure 12.10. Tip You’ll notice that in both our CSS and About sections we include images. To save on hosting and bandwidth costs, both images are hosted by MySpace. While logged in as the app to edit the Profile, we uploaded the photos through the Upload link on the Home page, just as normal users would upload their photos. Once the photos are uploaded, you can view the source of the image by right-clicking it and selecting Properties. Voilà! Free image hosting for MySpace apps! Figure 12.10 Updated Tic-Tac-Toe app Profile page. Please purchase PDF Split-Merge on to remove this watermark.
  6. Managing Developers 279 Managing Developers We already know how to edit the source code, details, and templates, but you can also use the developer platform to manage multiple developers. By clicking the Developers & Testers option under an app on the My Apps page, you can add and delete codevelopers. Once you click on Developers & Testers, you will be shown your friend list.To be added to your app, the developer must first be your MySpace friend. He or she must also be an approved developer; all of the approved developers in your friend list will have a gear icon under their pictures.To add a friend as a developer, click and drag his or her picture box into the Developers column.To remove the friend as a developer, simply click on the red circular icon in the Developers column next to the friend’s name. Before you grant developer status to anyone, it’s recommended that you back up your source code with every version of the app. Note You can’t set specific permissions for each codeveloper. Once someone is added as a developer to an app, the person can install the app in development status, make changes to the code, and even submit the app for publishing. However, the person can’t delete the app, add other developers, or acknowledge feedback. For example, if your app is denied publication because of an error, only you, the original developer, may acknowledge feedback and revert it to a ready-to-publish status. There’s one last kick in the pants. As long as you’re someone’s friend and an approved developer, that person can add you as a developer to his or her app and you can’t say no or remove yourself as a developer.The app creator must remove you. So, if someone adds you as a developer on a questionable app, such as a Battlestar Galactica Sucks app, your name will be attached to it publicly unless you ask the original creator very nicely to please remove you as a developer. Managing Testers You may want to have a few people test your app before you make it live, or test it yourself on different accounts.That’s smart. So, how do you do it? From the My Apps section of the developer platform, click the Developers & Testers link.You’ll be shown a list of your friends alongside a Developer column and a Test Users column. Simply drag and drop your friends over to the Test Users column to add them as testers. Once added, they’ll have instant access to your app in progress. Event Handling—Installs and Uninstalls The concept of signed data calls was covered extensively in Chapter 8, OAuth and Phoning Home, and it really comes into play here with an app’s Install Callback URL and Uninstall Callback URL.These two settings fields can be found under the Edit Details tab of your app and are shown in Figure 12.11. Basically, whenever a user installs or uninstalls your app, MySpace makes a signed request to these URLs and passes the user’s ID. So, other than the OAuth signature, it Please purchase PDF Split-Merge on to remove this watermark.
  7. 280 Chapter 12 App Life Cycle Figure 12.11 Callback URL settings. sends only one piece of information, the user’s ID.What you then choose to do with that piece of information is up to you. Some apps use the user IDs to simply track who has the app installed. Others may use them to create profiles for all the users and add them to an off-site database. Again, how you use the ID that’s passed in to your callback URLs is your decision. Suspension and Deletion of Your App Suspension is pretty rare in the world of MySpace apps. If an app violates the Terms of Use and gets past the reviewers, the app developer usually receives a warning before the app is suspended or shut down.The developer then has 24 hours (or however long is specified in the violation notice) to fix the problem.This is not set in stone, and if an app grossly violates the Terms of Use, or the law, it can be suspended immediately. Any suspension or violation notices are sent to the e-mail of the app’s creator (not the app’s e-mail address or the e-mail address of any codevelopers), so make sure you monitor your app developer e-mail address. Warning If your MySpace account is deleted for violating the MySpace Terms of Use, you will not be able to log in and manage your application. Even getting your now-orphaned application deleted can be a major headache. There is a work-around for this, though—don’t violate the Terms of Use. If your app is suspended, you need to fix the problem before the app is reinstated. So, while you can appeal on the forums, there is no quick fix if your app breaks the rules. Please purchase PDF Split-Merge on to remove this watermark.
  8. Summary 281 Summary If your app works and doesn’t violate the Terms of Use, you should have no problem getting it published and up and running. However, in the rare instance that an app is incorrectly flagged, we hope this chapter will help you navigate the ins and outs of app publishing. Remember, though, that it’s easier to catch flies with honey, so be courteous when dealing with the developer relations team. Note Code listings and/or code examples for this chapter can be found on our Google Code page under Please purchase PDF Split-Merge on to remove this watermark.
  9. This page intentionally left blank Please purchase PDF Split-Merge on to remove this watermark.
  10. 13 Performance, Scaling, and Security W e’re going to delve into some of the more esoteric aspects of building your app empire. It’s one thing to build a “Hello World” app, or even put together a small mashup. It’s something else entirely to build an app that becomes an everyday part of life for over a million people. Consistent performance and user trust become some of the most important aspects of your app. This chapter is not an exhaustive study of Web app performance. If you want to study Web app performance, there are many resources online.Yahoo! Developer Network has done some excellent research into performance and publishes the information online. You could also pick up any number of books on performance, such as High Performance Web Sites by Steve Souders. It is a large topic worthy of several books.We are, however, going to cover some of the basics, such as the difference between performance and scaling of an application and some design hints to improve your app’s ability to grow. Performance and Responsiveness To start this discussion we’re going to explore different aspects of performance. Performance is an overloaded term. Cars are often said to have good performance when they can reach top speed quickly and handle tight turns without sliding off the road. Another less common but equally correct statement is that a car has good performance if it gets good gas mileage and can travel long distances on a limited amount of fuel. People are often said to perform well on the job if they are able to handle multiple competing priorities simultaneously. It’s not that anything is getting done fast, but that lots of things are getting done. What Is Responsive Performance and What Is Scale Performance? Performance is generally discussed in terms of how responsive a system is: “When I click the button, does something happen immediately?”To borrow from the auto industry, responsive performance is your “zero-to-60” measure. If your app is like my boss’s Please purchase PDF Split-Merge on to remove this watermark.
  11. 284 Chapter 13 Performance, Scaling, and Security Ferrari, it’s doing the equivalent of zero to 60 in 3.5 seconds. If your app is more like my jalopy (a 1985 Toyota Tercel, engine factory-rated at 65 HP when it rolled off the assembly line), it’s doing zero to 60 in 35.0 seconds. A secondary, and less common, measure of performance is in terms of scale: “If everyone in the world pushes the button at the same time, does it still work?”This is equivalent to a hot summer day when everyone in the city turns on the air conditioning. If the power grid scales, everyone’s air conditioner continues to function and homes and apartments cool off. If the power grid doesn’t scale, as in California, everyone’s lights flicker or brown out.This behavior is not to be confused with the situation in the mid-nineties when a rat chewed through a main feeder line, which in turn blew some circuits and took down the Western power grid (a failure of robustness). Nor is it to be confused with events of the late nineties into the early twenty-first century when Enron was running its “Death Star” and “Fat Boy” projects to create artificial scarcity and brownouts so it could jack up the price and “relieve the congestion” (a failure of public policy). Design for Responsiveness Responsive performance is generally well understood. For years the common wisdom in many computing circles, particularly with Internet applications, was to ignore responsive performance and focus on feature delivery.The underlying assumption was that because computing power and network connection speeds were constantly improving, by the time a given product had reached market penetration, the underlying hardware and network speeds would have improved enough to account for poor performance designs in the early stages of development. An object example of this idea that hardware would fix all issues with software responsiveness can be witnessed in the early growth and attitudes of the Java community. Programming in Java was very powerful because of the rich and clean abstraction layer it provided.The promise of a cross-operating-system language that one could “write once, run anywhere” was very compelling. Unfortunately for Sun, the hardware performance envelope failed to progress quickly enough to account for the initial nonperforming virtual machine design. Over the course of a decade the JVM ( Java Virtual Machine) did improve and hardware did catch up, but the damage was done.Today, because of this and a number of other reasons, Java is almost never found in user-facing applications and user interfaces, for which it was originally designed. Instead, it is mostly relegated to back-end servers and some embedded applications. While CPU power continues its relentless Moore’s march, overall computer performance has hit a bit of a plateau. Much, if not most, of the excess computing power is being used for visual effects and to support more background processes and higher- level programming tools. Another major driver in this performance plateau, in our opinion, is the rise of Web applications and the underlying constraints of network latencies and Web browser rendering engines and JavaScript interpretation. Please purchase PDF Split-Merge on to remove this watermark.
  12. Performance and Responsiveness 285 Broadband connection speeds, at least in the United States, have been increasing more linearly (actually, probably more like cubically, but we’re not math majors), not exponentially. Back in 1993, when NCSA Mosaic first launched and brought the Web out of the doldrums of Telnet and IRC, most people who had private Internet access were connecting via 9600Bps or 14.4kBps modems. For a short while, connection speeds almost doubled every two years (following a path similar to Moore’s law) but have moved more slowly in recent years as broadband providers seek to wring profits from their networks by creating artificial product differentiation.Two recent studies put the average connection speed in the United States somewhere between 1.9 and 4.8MBps.A U.S. Department of Agriculture census found that in 2007 only 33% of all farms had broadband connections.That means the rest were still on 56K modems or had no connectivity at all.This is in contrast to Japan, which has an average broadband speed of 61MBps (about ten times what would be considered the upper half of U.S. connection speeds). Responsive performance has seen a bit of a renaissance in the last few years. New research into user interaction and how great the effect of response times is on user behavior has highlighted the importance of responsive design.A responsive product is now seen as a strategic differentiator in a world of me-too products.That and new research into what leads to a responsive design have given rise to a number of rules for writing Web apps. Basic Rules Here are some basic rules that every developer concerned with performance and responsiveness should know: n Place CSS styling at the top. n Place JavaScript, particularly includes, at the bottom. n Simplify your markup. At this point in time these rules are bordering on common wisdom, much as “Size your images” and “Make pages smaller” were in the late dot-com days. Responsive OpenSocial App Performance Guidelines There are also some less obvious guidelines that are specific to writing OpenSocial apps. These rules will help your app be more responsive when dealing with fetching and working with OpenSocial data. Following these guidelines will also help your app perform consistently and keep your users coming back rather than being annoyed by quirks and stutters when using your app. 1. Don’t re-request the same piece of data. 2. Prefetch record lists for paging. 3. Batch requests. 4. Handle your errors. We’ll cover each rule in greater detail in the following sections. Please purchase PDF Split-Merge on to remove this watermark.
  13. 286 Chapter 13 Performance, Scaling, and Security Rule 1: Don’t Re-Request the Same Piece of Data Many times when we review code, we see this mistake being made. Recently we were reviewing some code written in jQuery that was reselecting the same node each time it wanted to change a property: $("#navhead").addClass("enabled"); $("#navhead").text = "Welcome"; This business went on for another five lines. Because it was so convenient to reselect the node, the author mistook it for being free. In actuality each call went through a seven-layer call stack to select the node and add the jQuery extensions.The simple tune-up was to assign the result to a variable and reuse it: var navHead = $("#navhead"); navHead.addClass("enabled"); navHead.text = "Welcome"; This is fairly basic stuff.We know you jQuery people out there are saying, “Well, the dev should have just chained things.” True, but that is a jQuery-specific feature. Stick with us here for the example. The same rules apply for any piece of data being requested via the OpenSocial framework.The difference is that the performance ramifications are much more noticeable.Take the case of requesting the Viewer: function getViewer(myCallback){ var req = opensocial.newDataRequest(); var id = opensocial.IdSpec.PersonId.VIEWER; req.add(req.newFetchPersonRequest(id), "viewer"); req.send(function(data){ myCallback(data.get("viewer").getData()); }); } This call is fine—once.What if this code were to be called every single time the Viewer data was needed? Not only is that execution clunky with extra callbacks, but it’s unnecessarily slow. A better solution is to execute this call once, place the result in a vari- able, such as myAppStuff.Viewer, and read it from this variable every time it is needed. In the early versions of the MySpace OpenSocial container, the container code would actually make an XHR request to the REST endpoint to refetch the Viewer data every time this code was called. Over time, MySpace has made some good optimizations on the container side. Now, many data call results are either cached and re-served client-side or prefetched. Even with those optimizations, the code still executes a 20-function code call each time the data is re-requested. The MySpace optimizations for fetched data do not extend to the results of makeRequest calls. If your code is calling out to your servers or some other external server, only re-execute the call if you think the data might have changed. Please purchase PDF Split-Merge on to remove this watermark.
  14. Performance and Responsiveness 287 Rule 2: Prefetch Record Lists for Paging This performance enhancer is about both efficiency and responsiveness. Paging through a list of friends is a very common operation.There are two ways to do this: our way and the wrong way. ( Just kidding, but only a little.) We’ll start with a simple example.Your app wants to page through the Viewer’s list of friends, four at a time.The simple and obvious solution is to place code handlers under the Prev and Next links to create a newFetchPeopleRequest, passing in the start record and number of records to retrieve.The guts of the code appear something like this: var pageSize = 4; var curPage = 0; function loadFriendsPage(){ var dataReqObj = opensocial.newDataRequest(); var viewerReq; var viewerFriendsReq; var startNum = (curPage * pageSize) + 1; var idspec = opensocial.newIdSpec( {userId : 'VIEWER', groupId : 'FRIENDS'}); var requestOpts = {}; var fldEnum = opensocial.DataRequest.PeopleRequestFields; requestOpts[fldEnum.MAX] = pageSize; requestOpts[fldEnum.FIRST] = startNum; viewerFriendsReq = dataReqObj.newFetchPeopleRequest( idspec, requestOpts); dataReqObj.add(viewerFriendsReq, "viewerFriendsReq"); dataReqObj.send(loadFriendsPageCallback); var prev = document.getElementById("prevLink"); if(curPage == 0){ prev.className = "pageaction disabled"; } else{ prev.className = "pageaction enabled"; } } function loadFriendsPageCallback(data){ var elem = document.getElementById("currentFriends"); var label = document.getElementById("pageHeader"); var fData = data.get("viewerFriendsReq").getData(); Please purchase PDF Split-Merge on to remove this watermark.
  15. 288 Chapter 13 Performance, Scaling, and Security if(data.hadError()){ var err = "error: " + fData.getErrorMessage(); label.innerHTML = "error: "; return; } var startNum = (curPage * pageSize) + 1; var endNum = startNum + pageSize; label.innerHTML = "Friends " + startNum + " to " + endNum; var items = ""; fData.each(function(person){ var src = person.getField(opensocial.Person.Field.THUMBNAIL_URL); items += ""; items += person.getField(opensocial.Person.Field.NICKNAME); items += ""; }) elem.innerHTML = items; } function getPreviousFriends(){ if(curPage < 1){ return; } curPage--; loadFriendsPage(); } function getNextFriends(){ curPage++; loadFriendsPage(); } The code works fine. If you test it in a simple scenario, the performance is probably okay as well, provided it’s not during peak hours. Looking at the network traffic (see Figure 13.1) tells a more interesting story. Each request shown in the figure is approximately 150ms.That’s not much time in and of itself, but that time adds up. If the user goes through six pages, a full second of time is used waiting for the network.What’s more, if the user pages backward, the same data your app just had is re-requested.This violates Rule 1: Don’t re-request the same piece of data. If your app is simultaneously attempting to retrieve album information or communicate with another server, this design would add noticeable and unnecessary overhead. A better design, and one used by the FriendPicker widget, is to ask to preload all the data in the background, then page by moving through the local data list. In order to make this happen, we use most of the same code with two additional code elements: an Please purchase PDF Split-Merge on to remove this watermark.
  16. Performance and Responsiveness 289 Figure 13.1 Network traffic on a wasteful pager. array to hold all the friend information and a new display function. Here is a look at the modified method of retrieving the friend list: var pageSize = 4; var curPage = 0; var allMyFriends = []; function loadFriendsInfo(){ var dataReqObj = opensocial.newDataRequest(); var viewerReq; var viewerFriendsReq; var idspec = opensocial.newIdSpec( {userId : 'VIEWER', groupId : 'FRIENDS'}); var requestOpts = {}; var fldEnum = opensocial.DataRequest.PeopleRequestFields; requestOpts[fldEnum.MAX] = 100; requestOpts[fldEnum.FIRST] = 1; viewerFriendsReq = dataReqObj.newFetchPeopleRequest( idspec, requestOpts); dataReqObj.add(viewerFriendsReq, "viewerFriendsReq"); dataReqObj.send(loadFriendsPageCallback); } function loadFriendsPageCallback(data){ var fData = data.get("viewerFriendsReq").getData(); Please purchase PDF Split-Merge on to remove this watermark.
  17. 290 Chapter 13 Performance, Scaling, and Security if(data.hadError()){ var err = "error: " + fData.getErrorMessage() label.innerHTML = "error: "; return; } fData.each(function(person){ var src = person.getField(opensocial.Person.Field.THUMBNAIL_URL); var item = ""; item += person.getField(opensocial.Person.Field.NICKNAME); allMyFriends.push(item); }); showCurrentPage(); } You may notice that the code for these two methods is actually smaller. It’s also cleaner because the two methods simply deal with retrieving and managing the data.The basic information of each friend (name and image) is pushed into our new data array, allMyFriends. Display of the data is now external to the data retrieval methods and in the showCurrentPage method.This separation of concerns leads to more efficient and maintainable code. function showCurrentPage(){ var elem = document.getElementById("currentFriends") var label = document.getElementById("pageHeader") var startNum = (curPage * pageSize) + 1; var endNum = startNum + pageSize; label.innerHTML = "Friends " + startNum + " to " + endNum; var items = ""; if(startNum < allMyFriends.length){ for(var i=0; i < pageSize; i++){ if((startNum + i) >= allMyFriends.length ){ break; } items += allMyFriends[startNum+i] + ""; } } elem.innerHTML = items; var prev = document.getElementById("prevLink"); if(curPage == 0){ prev.className = "pageaction disabled"; } Please purchase PDF Split-Merge on to remove this watermark.
  18. Performance and Responsiveness 291 else{ prev.className = "pageaction enabled"; } } function getPreviousFriends(){ if(curPage < 1){ return; } curPage--; showCurrentPage(); } function getNextFriends(){ curPage++; showCurrentPage(); } Now each time the user clicks the Prev/Next link, the page is repainted with data coming from a local array variable, not across the network.The network traffic sniffer results shown in Figure 13.2 also tell the story. The initial request now takes 400ms. It happens only once, though.This image also displays all the traffic after scrolling back and forth through the list several times.These measurements were taken on an account with 52 friends.The step-by-step pager would have taken 1950ms to retrieve the same number of records—almost five times as long! Not only that, but it would have continued to waste network requests each time the user scrolled.To really see the difference, the user can click the Next link in quick succession in both implementations.The second displays smoothly and quickly.The first will occasionally stutter, then catch up. Sometimes it will skip pages and can even get out sync if the XHR responses are returned out of order. Figure 13.2 Network traffic on a good pager. Please purchase PDF Split-Merge on to remove this watermark.
  19. 292 Chapter 13 Performance, Scaling, and Security Rule 3: Batch Requests The OpenSocial spec has a built-in mechanism for batching requests. Use it. At the time of this writing, MySpace sends these requests individually, but if you write your code to batch things, when the batching performance optimization is made on the underlying MySpace container, your code will be able to take advantage of it immediately. For servers under your control, design your endpoints to deliver all the data your app needs to execute a given task in one shot.This may feel as if it’s violating the integrity of your code design, where each type of data gets its own endpoint, but it is a worthwhile optimization. As an example, say your app allows virtual flowers to be sent to a friend. The user has an allotment of credits for buying flowers. One design is to have one call to purchase the flowers, then a second call to request the user’s remaining credits and update the “available credit” display. A better design is to make a single request that purchases the flowers and returns the remaining available credits in the response.You just cut your server request load in half! Rule 4: Handle Errors Stability and robustness will be covered in more depth later in this chapter, but they’re worth touching on now. Often when an unhandled error occurs in program execution, the program is left in an indeterminate state—it doesn’t understand where it is. As it attempts to continue execution, it may make calls with insufficient or invalid inputs, generating even more errors. More often than one might think, a program descends into a state of thrash— alternately requesting one piece of data incorrectly, getting a bad response, requesting a different piece of data incorrectly, getting a bad response, and ultimately descending into an infinite loop, thrashing back and forth between requests until a stack overflow happens or the browser pegs the CPU and has to be forcefully killed. If this sort of error happens often enough with your app, it may come to the attention of MySpace.When that occurs, you are typically given a few hours to rectify things. If the errors are bad enough that your app is adversely affecting other apps by tying up connections or causing user Home pages to crash, it may even be summarily suspended. Handle your errors. Design for Scale An application is said to “scale” if it maintains its performance characteristics while the number of users increases dramatically. MySpace scales. At the time of this writing, MySpace has in excess of 150 million unique users. Friendster did not scale. It predated MySpace and had more users initially, but once it hit some level of critical mass, the system froze and became nonresponsive. As a result, everyone left and moved to MySpace. Please purchase PDF Split-Merge on to remove this watermark.
  20. Design for Scale 293 Application Scale Definitions Applications are typically designed to perform and scale within one of these definitions: 1. Small/Workgroup Typified by a user base of fewer than 100 users/month. Mom-and-pop Web sites, niche e-commerce sites, and internal IT projects designed to address the needs of a single workgroup fall into this range. Deployments are usually single-server or partial-server (a server hosting several applications). 2. Enterprise Enterprise-scale applications are designed to satisfy the needs of an entire organiza- tion or a large part of an organization, servicing anywhere from a few hundred to tens of thousands of users. They tend to be industry-specific, like a medical records man- agement system or a payroll system. Deployments may be to a single dedicated server or a small cluster (three to five computers). Classic relational databases and reporting systems are very common. Enterprise applications are almost never consumer-oriented. 3. Internet Internet-scale applications may service from several hundred thousand to several hundred million users. Internet-scale applications are almost always consumer- oriented, although some also provide business-oriented features. These applications have unique designs to reach their performance needs. The architecture appears foreign to anyone trained solely in classic computer science and data modeling and seems to break many core rules. Deployments are across tens, hundreds, or even thousands of servers and must be able to handle individual server failures. There are several applicable guidelines to keep in mind when designing for scale.The sidebar “Application Scale Definitions” identifies different scaling terms to consider. At MySpace, the developers think only in Internet scale. As an app developer who could reach millions of users, you should also be thinking in Internet scale. App Guidelines for Internet-Scale Performance Here are some simple guidelines to consider when designing for scale. Follow these rules and you won’t get tripped up by some of the most common scaling mistakes. 1. Know your scaling point. 2. Identify scaling bottlenecks. 3. Remember what you know. 4. Scale horizontally. 5. Move beyond relational databases. Please purchase PDF Split-Merge on to remove this watermark.
Đồng bộ tài khoản